1

I came from the world of Python. I want to only get the positive number and set non-positive number to be zero. In Python:

>> a = [1,2,3,-1,-2, 0,1,-9]
>> [elem if elem>0 else 0 for elem in a]
[1, 2, 3, 4, 0, 0, 0, 1, 0]

Say I have a vector in R, how can I get the same result.

a <- c(1,2,3,-1,-2, 0,1,-9)
4

1 回答 1

6

利用ifelse

> ifelse(a>0, a, 0)
[1] 1 2 3 0 0 0 1 0

详情见?ifelse

您还可以使用[选择那些满足条件 ( a<=0) 的值并将它们替换为 0

> a[a<=0] <- 0
> a
[1] 1 2 3 0 0 0 1 0

?"["

a<=0将为您提供一个布尔向量,您可以将其用作索引来识别小于或等于 0 的值,然后执行所需的替换。

虽然使用[ifelse是最常见的,但在这里我提供了一些其他选择:

a[which(a<=0)] <- 0       
#----------------------
a[a %in% 0:min(a)] <- 0    # equivalent to a[!a %in% 0:max(a)] <- 0 
#----------------------
match(a, 1:max(a), nomatch=0 )
#----------------------
pmax(a, 0)
于 2013-10-24T16:48:41.297 回答