简体   繁体   中英

logical vector subsetting in R

I'm writing a function in R and I got stuck in a vector subsetting.

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.

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.:

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

because when I use

if

I obtain a NULL vector as

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. This rarely happens, so you can safely forget about 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. 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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