R list comprehension if else [duplicate]

2019-07-27 09:29发布

问题:

This question already has an answer here:

  • Replace negative values by zero 3 answers

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)

回答1:

Use ifelse

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

see ?ifelse for details.

you can also use [ to select those values meeting the condition (a<=0) and replace them by 0

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

see ?"[".

a<=0 will give you a boolean vector and you can use it as index to identify those values smaller or equal to 0 and then performing the desired replacement.

Although using either [ or ifelse are the most common, here I give some other alternatives:

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)