R unless otherwise

I came from the world of Python. I want to get only a positive number and set a non-positive number to 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] 

Let's 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
r list-comprehension
source share
1 answer

Use ifelse

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

See ?ifelse more details.

you can also use [ to select those values ​​that match the condition ( a<=0 ) and replace them with 0

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

see ?"[" .

a<=0 will provide you with a logical vector, and you can use it as an index to identify those values ​​that are less than or equal to 0, and then perform the required replacement.

Although the use of [ or ifelse is the most common, here are some other options:

 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) 
+4
source share

All Articles