简体   繁体   中英

Fill vector with sequence

Can you explain me, why, when i fill vector in R with sequence, i ve got this result:

sekv <- seq(from = 1, to = 20, by = 2)
test <- c()
for (j in sekv) {
    test[j] = j
}
test
[1]  1 NA  3 NA  5 NA  7 NA  9 NA 11 NA 13 NA 15 NA 17 NA 19

I want make a vector, which i can fill with some sequence and use it in loop, but only with values, not with NA values. Can somebody help me ?

In sekv you currently pass 2.. 4 ..6, use seq_along

   sekv <- seq(from = 1, to = 20, by = 2)
    test <- c()
    for (j in seq_along(sekv)) {
      test[j] = j
    }
     test

The reason why you have NAs in the test vector is that you assign the first, third, fifth, seventh, etc element in the test vector to be 1, 3, 5, 7 etc...

I am still not very clear what you are trying to do, but one solution is that you can remove all the NAs after the for loop.

sekv <- seq(from = 1, to = 20, by = 2)
test <- c()
for (j in sekv) {
  test[j] = j
}
test
# [1]  1 NA  3 NA  5 NA  7 NA  9 NA 11 NA 13 NA 15 NA 17 NA 19
test <- test[-c(which(is.na(test)))]
test
# [1]  1  3  5  7  9 11 13 15 17 19

As @PoGibas suggested, this also works if you want to remove NAs:

test <- na.omit(test) 
test
# [1]  1  3  5  7  9 11 13 15 17 19

The actual issue is that whenever your are trying to assign value to test[j] it using value of j to change the size of the vector. The last value of j is 19 hence size of test is set to 19. But you have assigned value only to few indexes ie 1, 3, 5 etc. Rest of values are set to NA.

You can solve it by executing for loop only for number of items available in sekv .

sekv <- seq(from = 1, to = 20, by = 2)
test <- c()
for (j in 1:length(sekv)) {
    test[j] = sekv[j]
}
print(test)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM