Vector of elements satisfying a condition in r project -


in code r:

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

i have output

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

but need vector of i´s satisfies condition, ie (1,3,5,7,9). how can vector (without knowing in advance vector dimension "length")?

the above example of 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, need matrix elements.

in many ways. here's one:

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

an alternative:

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

a version of first 1 people hate type:

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

if you'll need sort of thing should write function, this:

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

or

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

... or both. can stuff like

i[odd(i)] [1] 1 3 5 7 9 

Comments