我有一個包含多列的資料框,我正在使用 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])
}
但是,它給了我以下錯誤:
Error in $<-.data.frame( *tmp*, "distance", value = c(NA, 0.194077783375631 : replacement has 2 rows, data has 4837
我的資料框中有 4837 行。我有許多其他資料框,我正在應用相同的代碼并且它正在作業,但在這里和其他一些資料框中,它不起作用。
我在谷歌驅動器中添加了帶有資料的 .CSV 檔案:鏈接到 csv 檔案
uj5u.com熱心網友回復:
您的 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 的前置步驟的操作放在回圈之外是很聰明的。這將為您節省未來的計算時間。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/408651.html
標籤:
