others - source(): Error: Replacement has length zero

我无法找出问题可能在哪里,也没法提供一些示例数据:


for (i in 1:nrow(df)) {


 if(df$Species[i]=="Fi"){


 print(i)


 df$`Length Beech 2019 [cm]`[i] <- df$`Height [cm] 2019`[i] - df$`Höhe Spruce 2018 [cm]`[i]


 } 


}



这部分在同一个脚本中运行完美。 但是如果我将重新填充dataframe的整个过程复制到另一个R脚本中,


> source("2 RedesignDF.R")


[1] 2


Error in df$`Length Beech 2019 [cm]`[i] <- df$`Height [cm] 2019`[i] - : 


 replacement has length zero



我得到这个错误,前10个值是:


> str(df$`Length Beech 2019 [cm]`)


 num [1:113] 25 NA NA 25 23 NA 14.5 19.5 NA NA ...


> str(df$`Height [cm] 2019`)


 num [1:113] 302 186 188 306 258 ...


> str(df$`Höhe Spruce 2018 [cm]`)


 num [1:113] NA 176 178 NA NA ...



我做了一些样本数据:


Species <- c("Bu","Fi","Fi","Bu","Bu","Fi","Bu","Bu","Fi","Fi")


`Length Beech 2019 [cm]` <- c(15.5, NA, NA, 23, 20, NA, 14, 18.5, NA, NA)


`Height [cm] 2019` <- c(298, 179.5, 306.5, 306.5, 258.5, 188.5, 186, 301.5, 244, 192)


`Höhe Spruce 2018 [cm]` <- c(NA, 169.5, 271, NA, NA, 170, NA, NA, 233.5, 188)



df <- data.frame(Species, `Length Beech 2019 [cm]`, `Height [cm] 2019`, `Höhe Spruce 2018 [cm]`)



时间:

我已经修改了你的代码,它产生了输出,你也可以尝试另一个r脚本。


for (i in 1:nrow(df)) {


 if(df$Species[i]=="Fi"){


 print(i)


 df$Length.Beech.2019..cm.[i] <- 


 df$Height..cm..2019[i] - df$Höhe.Spruce.2018..cm.[i]


 } 


}



我找到了答案,源无法与, ,ü 和. 一起使用。因此,必须删除这些,或者指定编码。


source("2 RedesignDF.R", encoding ="UTF-8")



...