For loop in R starting from other value -


this has been bothering me time now. imagine have to/want use loop.

if write loop, want start number 2, you'd use following:

for (i in 2:length(variable1) { ... } 

the problem arises when try assign values such:

variable2 <- 1:length(variable1) (i in 2:length(variable1) {     variable2[i] <- sample(variable1, 1)  # silly example; ignore content-wise } 

now, no matter if have smaller vector initialized, problematic obtained variable2, since has "1" in first position. easiest way deal loop when want start higher number? , there better way having use i <- i+i, since have let run 1 length(variable1) minus 1. missing easy solution?

while @ it, best way predefine variable before for loop? use variable2 <- 1:length(variable1), when know variable2 should variable length of variable1. fastest way allocate memory?

edit: kind of realized might easiest do:

variable2 <- 2:length(variable1) (i in 2:length(variable1) {     variable2[i-1] } 

but still open better suggestions.

don't hardcode beginning index.

from <- 2 <- length(variable)  (i in from:to) {    variable2[i - + 1] <- sample(variable1, 1) }  

or, if find more expressive

offset <- 1 <- length(variable)  for(i in (offset + 1):to) {    variable2[i-offset] <- sample(variable1, 1) } 

Comments

Popular posts from this blog

linux - Does gcc have any options to add version info in ELF binary file? -

android - send complex objects as post php java -

charts - What graph/dashboard product is facebook using in Dashboard: PUE & WUE -