R - write value into variable after two statements -
i have loop 2 if statements. works fine, except add values passing second if statement variable v1. assign variable first , variable gets filled lot of na's , 3 values expecting. want 3 values in variable.
so instead of writing i
fulfills requirements, every single i
gets written variable.
v1 <- c() for(i in seq_along(y$values)){ if(y$lengths[i] < 500 && y$values[i] == true){ y$values[i] <- false } if(y$lengths[i] > 500 && y$values[i] == true){ print(y$lengths[i]) v1[[i]] <- y$lengths[i] } }
i had @ apply functions, couldn't figure out how use both if statements in apply.
the data large logical vector. use y <- rle(vec)
on vector, gives me y$lengths
(everything between 1 , few hundred thousand) , y$values
(true , false).
the desired result rle lengths >500 , true true.:
[1] 5120 [1] 16630 [1] 10188
which print command gives me fine.
dput(y$length)
gives me:
c(129719l, 1l, 79337l, 2l, 4l, 1l, 3l, 1l, 2l, 1l, 1l, 1l, 4l, 2l, 2l, 3l, 2l, 1l, 2l, 2l, 2l, 2l, 2l, 1l, 1l, 5l, 1l, 3l, 1l, 6l, 1l, 5120l, 1l, 39l, 1l, 12l, 1l, 121l, 1l, 14l, 1l, 6l, 1l, 3l, 1l, 3l, 1l, 2l, 1l, 6l, 1l, 11l, 1l, 9l, 1l, 10l, 2l, 6l, 1l, 2l, 2l, 1l, 1l, 7l, 2l, 4l, 1l, 2l, 1l, 4l, 1l, 3l, 2l, 5l, 1l, 5l, 4l, 8l, 1l, 4l, 1l, 4l, 2l, 2l, 2l, 9l, 1l, 2l, 1l, 2l, 1l, 3l, 2l, 1l, 1l, 1l, 1l, 1l, 1l, 1l, 2l, 2l, 1l, 3l, 3l, 1l, 7l, 1l, 1l, 1l, 1l, 2l, 6l, 2l, 2l, 1l, 2l, 4l, 3l, 1l, 1l, 1l, 4l, 3l, 2l, 1l, 5l, 5l, 2l, 2l, 3l, 1l, 2l, 1l, 1l, 1l, 2l, 1l, 4l, 2l, 2l, 1l, 1l, 1l, 4l, 1l, 1l, 3l, 4l, 2l, 1l, 1l, 13l, 1l, 3l, 2l, 3l, 1l, 9l, 1l, 1l, 1l, 1l, 2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16l, 1l, 22l, 1l, 1l, 1l, 10l, 1l, 20l, 1l, 18l, 1l, 20l, 1l, 3l, 1l, 2l, 1l, 2l, 1l, 5l, 1l, 9l, 1l, 3l, 1l, 3l, 1l, 15l, 1l, 10l, 1l, 40l, 1l, 30l, 1l, 111l, 1l, 314l, 1l, 9l, 1l, 10188l, 4l, 88l, 1l, 8l, 1l, 1l, 1l, 1l, 1l, 15l, 1l, 24l, 1l, 1l, 2l, 3l, 1l, 16l, 1l, 3l, 1l, 4l, 2l, 2l, 2l, 1l, 2l, 5l, 2l, 2l, 7l, 1l, 1l, 3l, 2l, 3l, 7l, 2l, 1l, 1l, 6l, 1l, 4l, 2l, 2l, 1l, 2l, 1l, 1l, 1l, 13l, 1l, 2l, 1l, 2l, 1l, 3l, 1l, 3l, 1l, 4l, 1l, 16l, 1l, 4071l, 5l, 162912l, 1l, 6l, 1l, 280986l)
you can final v1 vector efficiently without loops or apply this:
v1 <- y$lengths[y$lengths > 500 & y$values == true]
if want use loops here 2 options:
(1) can append v1 this:
v1 <- c() for(i in seq_along(y$values)){ if(y$lengths[i] < 500 && y$values[i] == true){ y$values[i] <- false } if(y$lengths[i] > 500 && y$values[i] == true){ print(y$lengths[i]) v1 <- c(v1, y$lengths[i]) } }
(2) appending can slow if vector v1 gets long. alternative can preallocate exclude nas in end this:
v1 <- rep(na, length) for(i in seq_along(y$values)){ if(y$lengths[i] < 500 && y$values[i] == true){ y$values[i] <- false } if(y$lengths[i] > 500 && y$values[i] == true){ print(y$lengths[i]) v1[i] <- y$lengths[i] } } v1 <- v1[!is.na(v1)]
Comments
Post a Comment