在 R 数据帧的行操作中使用 for 循环时如何解决错误?

How can I solve the error while using the for loop in a row operation in R data frame?

我有一个包含多列的数据框,我正在使用 for 循环来应用正在记录在新列中的数学运算。数据框名为“F39”。我写的代码如下:

for (i in 2:nrow(F39)) {
 #calculating distance from distance formula (both in x and y)
F39$distance[i] <- sqrt((F39$X..cm.[i]-F39$X..cm.[i-1])^2 + (F39$Y..cm.[i]-F39$Y..cm.[i-1])^2)
#calculating fish speed in x and y
F39$fishspeed[i] <- F39$distance[i]/(0.02)
#assigning 0 as the starting fish speed
F39$fishspeed[1] <- 0
#assigning positive and negative signs to the velocity 
F39$fishspeed[i] <- ifelse(F39$X..cm.[i]-F39$X..cm.[i-1] < 0,F39$fishspeed[i],-F39$fishspeed[i])
}

但是,它给了我以下错误: 错误 $<-.data.frame(*tmp*, "distance", value = c(NA, 0.194077783375631 : 替换有 2 行,数据有 4837

我的数据框中有 4837 行。我有许多其他数据框,我在其中应用相同的代码并且它正在工作,但在这里和其他一些数据框中,它不起作用。

我已经在 google 驱动器中添加了包含数据的 .CSV 文件:Link to csv file

您的 data.frame 缺少“距离”一栏。因此它无法使用语法 F39$distance[i] <- ...

在此列中保存任何值

解决方案是先创建列,然后再进行迭代,例如

F39 <- read.csv("C:/Users/kupzig.HYDROLOGY/Downloads/Fish39.csv")
names(F39) #-> no distance as column name

F39$fishspeed[1] <- 0 #assigning 0 as the starting fish speed
F39$distance <- NA #create the distance column

for (i in 2:nrow(F39)) {
  #calculating distance from distance formula (both in x and y)
  F39$distance[i] <- sqrt((F39$X..cm.[i]-F39$X..cm.[i-1])^2 + (F39$Y..cm.[i]-F39$Y..cm.[i-1])^2)
  #calculating fish speed in x and y
  F39$fishspeed[i] <- F39$distance[i]/(0.02)
  #assigning positive and negative signs to the velocity 
  F39$fishspeed[i] <- ifelse(F39$X..cm.[i]-F39$X..cm.[i-1] < 0,F39$fishspeed[i],-F39$fishspeed[i])
}

请注意,将所有独立于 i 或独立于任何其他依赖于 i 的前置步骤的操作都放在循环之外会很聪明。这样可以节省你以后的计算时间。