which - R look for specific value in data.frame row by row -


i've got dataframe (maturgi) composed ntraj lines , 91 columns. want save position index corresponding first time value of given row superior threshold (here: 27.66)).

i tried following scripts

    for(i in 1:ntraj) {     z <- min(which((maturgi[i,]>27.66),arr.ind=true))     print(z)   } 

and

    trial <- function(x){   for(i in 1:x) {     z <- min(which((maturgi[i,]>27.66),arr.ind=true))     rbind(z)   }   return(data.frame(cbind(z))) } 

yet, saved value corresponding last row instead of whole sequence. how can make it? in advance!

you overwriting z @ each iteration. obvious solution make z sufficiently big hold results before start looping, and assign each result different element of z. example

z <- numeric(length = ntraj)  for(i in seq_len(ntraj)) {     z[i] <- min(which(maturgi[i,] > 27.66, arr.ind = true)) }  z 

of course, can without looping , hence without having worry storage. also, can compute entire set of indices matching criteria ( > 27.66 ) in single step. example, using dummy data, minimum column index values > 0.25.

df <- data.frame(matrix(runif(100), ncol = 10)) ## dummy data 

you can compute entire index vector in 1 go

> df > 0.25          x1    x2    x3    x4    x5    x6    x7    x8    x9   x10  [1,]  true  true  true  true  true  true  true  true  true  true  [2,] false  true false false  true  true false  true  true  true  [3,] false  true  true  true  true  true  true false  true  true  [4,] false false  true  true false  true  true  true false  true  [5,]  true  true  true false  true false  true  true  true false  [6,] false false  true  true  true  true  true  true  true  true  [7,]  true false false false  true  true  true false  true  true  [8,] false  true false false  true false  true  true  true  true  [9,]  true  true  true  true false  true  true false false  true [10,] false  true  true false  true  true  true  true  true false 

and use in apply() call. direct translation of loop is

> apply(df > 0.25, 1, function(x) min(which(x, arr.ind = true)))  [1] 1 2 2 3 1 3 1 2 1 2 

but simpler solution use which.max(), noting false == 0 , true == 1 , which.max (and cousin which.min()) returns first of values taking maximum (or minimum). hence

> apply(df > 0.25, 1, which.max)  [1] 1 2 2 3 1 3 1 2 1 2 

which pretty succinct...


Comments

Popular posts from this blog

basic authentication with http post params android -

vb.net - Virtual Keyboard commands -

css - Firefox for ubuntu renders wrong colors -