我正在尝试在 R 中为一个大型进程编写一些代码,但我不断收到此错误:
Example <- data.frame(Col1 = c(1, 2, 3, 4, 5),
COl2 = c("A", "B", "C", "D", "E"))
Example[Example$Col1 > 3,]$Col1 <- 3 #works fine, 2 rows were selected
Example[Example$Col1 < -5,]$Col1 <- 0 #gets an error, 0 rows were selected
Error in `$<-.data.frame`(`*tmp*`, Col1, value = 0) :
replacement has 1 row, data has 0
我知道导致错误的原因是选择了零行,因此无法进行替换。但是对于我的工作过程,我不介意是否跳过该行。
我知道我可以通过 if 来避免它:
if(sum(Example$Col1 < -5) > 0){
Example[Example$Col1 < -5,]$Col1 <- 0
}
但我想知道是否有更简单(或更清洁)的方法来做到这一点。任何提示?
最佳答案
改为这样写:
Example$Col1[Example$Col1 > 3] <- 3
Example$Col1[Example$Col1 < -5] <- 0
关于R 数据帧错误 - 替换有 1 行,数据有 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47001491/