R convert vector of numbers to skipping indexes -


i have vector of widths,

ws = c(1,1,2,1,3,1) 

from vector i'd have vector of form:

indexes = c(1,2,3,5,6,7,9,11,12) 

in order create such vector did following loop in r:

ws = c(1,1,2,1,3,1) indexes = rep(0, sum(ws)) counter = 1 counter2 = 1 last = 0 for(i in 1:length(ws)) {   if (ws[i] == 1)   {     indexes[counter] = counter2     counter = counter + 1   } else {     for(j in 1:ws[i])     {       indexes[counter] = counter2       counter = counter + 1       counter2 = counter2+2     }     counter2 = counter2 - 2   }   counter2 = counter2+1 } 

the logic follows, each element in ws specifies respective number of elements in index. example if ws 1, respective number of elements in indexes 1, if ws > 1, let 3, respective number of elements in index 3, , elements skipped 1-by-1, corresponding 3,5,7.

however, i'd avoid loops since tend slow in r. have suggestions on how achieve such results vector operations? or more crantastic solution?

thanks!

here's vectorized one-liner you:

ws <- c(1,1,2,1,3,1)  cumsum((unlist(sapply(ws, seq_len)) > 1) + 1) # [1]  1  2  3  5  6  7  9 11 12 

you can pick apart piece piece, working inside out, see how works.


Comments

Popular posts from this blog

c# - How Configure Devart dotConnect for SQLite Code First? -

java - Copying object fields -

c++ - Clear the memory after returning a vector in a function -