【问题标题】:How can I solve the error while using the for loop in a row operation in R data frame?在 R 数据框中的行操作中使用 for 循环时如何解决错误?
【发布时间】:2022-01-10 11:16:24
【问题描述】:

我有一个包含多列的数据框,我正在使用 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])
}

但是,它给了我以下错误: $&lt;-.data.frame(*tmp*, "距离", value = c(NA, 0.194077783375631 中的错误: 替换有2行,数据有4837

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

我在 google 驱动器中添加了带有数据的 .CSV 文件:Link to csv file

【问题讨论】:

    标签: r dataframe for-loop row


    【解决方案1】:

    您的 data.frame 缺少“距离”列。因此,它无法使用语法F39$distance[i] &lt;- ... 在此列中保存任何值

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

    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 的前置步骤的操作放在循环之外是很聪明的。这将为您节省未来的计算时间。

    【讨论】:

    • 谢谢。但我想知道为什么我发布的代码适用于某些数据帧而不适用于其他数据帧?
    • 您是否检查过其他 data.frames 是否有“距离”列?如果是这样,“旧”列只会被您的代码覆盖,您不会收到任何错误。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-09
    • 1970-01-01
    • 1970-01-01
    • 2016-12-08
    • 2020-01-08
    • 2021-08-01
    • 1970-01-01
    相关资源
    最近更新 更多