R列表理解,否则 [英] R list comprehension if else

查看:76
本文介绍了R列表理解,否则的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我来自Python世界. 我只想获取正数并将非正数设置为零. 在Python中:

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]

说我在R中有一个向量,我怎么能得到相同的结果.

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

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

推荐答案

使用ifelse

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

有关详细信息,请参见?ifelse.

see ?ifelse for details.

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

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

请参阅?"[".

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

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.

尽管最常见的是使用[ifelse,但在这里我给出了一些其他选择:

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)

这篇关于R列表理解,否则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆