R中的逻辑向量子集

以法莲

我在R中编写函数,但陷入了向量子集。

假设我有以下向量:

  ratio<-c(0,0,0,0,1.3,1.4)

我想将所有值> 0且如果存在一个或多个0的向量子集化,我想在最终向量中仅包含一个0。

预期产量:

subset<-(0,1.3,1.4)

我尝试了以下方法:

sebset1<-ratio[ratio>0]
subset1
[1] 1.3 1.4

然后,我使用了以下情况:

subset2<- if(c(ratio==0)) {append (subset1, 0,after=length(subset1))}

我收到此警告:

Warning message:
In if (c(ratio == 0)) { :the condition has length > 1 and   only the first element will be used

但它有效:

subset2
[1] 1.3 1.4 0.0

但是,此解决方案不适用于不带0的向量,例如:

ratio2<-c(3,4,2,3,4)

因为当我使用

if

我得到一个NULL向量为

subset2

有什么想法可以改进我的代码吗?

非常感谢您的帮助!

vrajs5

试试这个。。没有子集

#if ratio's value between 0 to +Inf
mysubset = c(ratio[ratio>0],unique(ratio[ratio==0]))

#if ratio's value between -Inf to +Inf and you want to remove only zero like you mentioned in question 
mysubset = c(ratio[ratio!=0],unique(ratio[ratio==0]))

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章