简体   繁体   English

R中的逻辑向量子集

[英]logical vector subsetting in R

I'm writing a function in R and I got stuck in a vector subsetting. 我在R中编写函数,但陷入了向量子集。

Let's assume I have the following vector: 假设我有以下向量:

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

I would like to subset the vector taking all values > 0 and IF one or more 0 are present I want to include in the final vector only one 0. 我想将所有值> 0且如果存在一个或多个0的向量子集化,我想在最终向量中仅包含一个0。

Expected output: 预期产量:

subset<-(0,1.3,1.4)

I tried the following: 我尝试了以下方法:

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

Then I used if: 然后,我使用了:

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

I get this warning: 我收到此警告:

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

But it works: 但它有效:

subset2
[1] 1.3 1.4 0.0

However, this solution does not work for vector that have no 0, for ex.: 但是,此解决方案不适用于不带0的向量,例如:

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

because when I use 因为当我使用

if

I obtain a NULL vector as 我得到一个NULL向量

subset2

Any idea where I can improve my code? 有什么想法可以改进我的代码吗?

Thank you very much for your help! 非常感谢您的帮助!

Structuring the code like this most closely resembles your description of the algorithm in English: 像这样构造代码最类似于您对英语算法的描述:

filtered.ratio <- ratio[ratio > 0]
if (any(ratio == 0)) {
  filtered.ratio <- c(filtered.ratio, 0)
}

Note that append is really only preferred over c when elements need to be inserted at an internal position in a vector. 请注意,实际上只有在元素需要在向量的内部位置插入时, append才比c更好。 This rarely happens, so you can safely forget about append . 这种情况很少发生,因此您可以放心地忽略append

Try this.. Its without subset 试试这个。。没有子集

#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]))

the if command in R is not vectorised, so if(ratio==0) only compares the first element to zero, so won't work if the first zero is later in the vector. R中的if命令未向量化,因此if(ratio==0)仅将第一个元素与零进行比较,因此如果第一个零在向量中的后面将不起作用。 Try: 尝试:

subset1 <- ratio[ratio>0]
if(any(ratio==0)) subset2 <- c(0,subset1) else subset2 <- subset

Note also that if returns NULL when the test is FALSE and there is no else part, that's what's causing your problems with NULL . 还要注意,如果在测试为FALSE时返回NULL ,并且没有else部分,那就是导致NULL问题的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM