Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vector of elements satisfying a condition in r project

Tags:

r

in code R:

for (i in 1:10) {
  if (!i %% 2){
    next
  }
  print(i)
}

I have as output

[1] 1
[1] 3
[1] 5
[1] 7
[1] 9

But I need the vector of i´s that satisfies that condition, ie (1,3,5,7,9). How can I get the vector (without knowing in advance the vector dimension "length")?

The above is an example of my problem:

 x=c(0.1,0.4,0.5)
   y=c(0.2,0.3,0.6,0.7) 

 cont1=0
  for(i in 1:(length(x)+1)){

    for(j in 1:(length(y)+1)){

        if(round((abs((j-1)-(i-1)*(length(y)/length(x))) ),3)  < round( max.v.d,3) ) {
         cont1=cont1+1
         print(paste(i-1,j-1))
          }

    }
  }

output

[1] "0 0"
[1] "0 1"
[1] "1 1"
[1] "1 2"
[1] "2 2"
[1] "2 3"
[1] "3 3"
[1] "3 4"

but, I need a matrix with those elements.

like image 528
albert Avatar asked Oct 22 '25 17:10

albert


1 Answers

in many ways. Here's one:

i <- 1:10
i[as.logical(i%%2)]

an alternative:

i[(i%%2)==1]

a version of that first one for people who hate to type:

 i=1:10
 i[!!(i%%2)]

If you'll need to do this sort of thing often you should probably write a function, something like this:

 odd <- function(x) x%%2 != 0

or

 even <- function(x) x%%2 == 0

... or both. Then you can do stuff like

i[odd(i)]
[1] 1 3 5 7 9
like image 182
Glen_b Avatar answered Oct 25 '25 07:10

Glen_b



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!