你可以使用这个which功能:
sample <- c(1, 2, -7, NA, NaN)
sample[which(sample > 0)]
[1] 1 2
Run Code Online (Sandbox Code Playgroud)
对于负值,指定NA.
使用which:
sample[which(sample < 0)] <- NA
Run Code Online (Sandbox Code Playgroud)
您可以尝试以下命令:
> x<-c(1,2,3,-5)
> x[x>0]
[1] 1 2 3
Run Code Online (Sandbox Code Playgroud)
将返回所有正值。
要将负数替换为 NA,请使用
> x <- ifelse(x<0, NA,x)
> x
[1] 1 2 3 NA
Run Code Online (Sandbox Code Playgroud)
选择正值的另一种方法是使用sign
x[sign(x) == 1]
Run Code Online (Sandbox Code Playgroud)
我们可以将它们结合起来Filter
Filter(function(i) i > 0, x)
Filter(function(i) sign(i) == 1, x)
Run Code Online (Sandbox Code Playgroud)