R 数据帧错误 - 替换有 1 行,数据有 0

RMo*_*ero 6 replace r dataframe

我正在尝试在 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
Run Code Online (Sandbox Code Playgroud)

我知道导致错误的原因是选择了零行,因此无法进行替换。但是对于我的工作过程,我不介意是否跳过该行。

我知道我可以通过 if 来避免它:

if(sum(Example$Col1 < -5) > 0){
    Example[Example$Col1 < -5,]$Col1 <- 0
}
Run Code Online (Sandbox Code Playgroud)

但我想知道是否有更简单(或更清洁)的方法来做到这一点。任何提示?

Sto*_*ica 5

改为这样写:

Example$Col1[Example$Col1 > 3] <- 3
Example$Col1[Example$Col1 < -5] <- 0
Run Code Online (Sandbox Code Playgroud)