R and record entries without the same length are zero

Let's say I have two vectors v1 and v2 and that I want to call rbind(v1, v2) . However, length(v1) > length(v2) assumed. I read from the documentation that a shorter vector will be reworked. Here is an example of this "recycling":

 > v1 <- c(1, 2, 3, 4, 8, 5, 3, 11) > v2 <- c(9, 5, 2) > rbind(v1, v2) [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] v1 1 2 3 4 8 5 3 11 v2 9 5 2 9 5 2 9 5 
  • Is there any simple way I can stop v2 from being reused and instead make the remaining entries 0?
  • Is there a better way to create vectors and matrices?

All help is much appreciated!

+4
source share
3 answers

use the following:

 rbind(v1, v2=v2[seq(v1)]) [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] v1 1 2 3 4 8 5 3 11 v2 9 5 2 NA NA NA NA NA 

Why it works: Indexing a vector with a value greater than its length returns the value NA at this index point.

  #eg: {1:3}[c(3,5,1)] #[1] 3 NA 1 

Thus, if you index shorter one of the indexes of the longer one, you will get all the values โ€‹โ€‹of the shorter plus a series of NA 's


Generalization:

 v <- list(v1, v2) n <- max(sapply(v, length)) do.call(rbind, lapply(v, `[`, seq_len(n))) 
+14
source

If you have many rbind vectors, finding longer and shorter vectors can be tedious. In this case, this is an option:

 require(plyr) rbind.fill.matrix(t(v1), t(v2)) 

or,

 rbind.fill(as.data.frame(t(v1)), as.data.frame(t(v2))) 
+2
source

Although I think Ricardo proposed a nice solution, a similar action would also work by applying a function to the list of vectors that you want to link. You can also specify the character to fill.

 test <- list(v1,v2) maxlen <- max(sapply(test,length)) fillchar <- 0 do.call(rbind,lapply(test, function(x) c(x, rep(fillchar, maxlen - length(x) ) ))) 

Or avoid all the madness of do.call(rbind :

 t(sapply(test, function(x) c(x, rep(fillchar, maxlen - length(x))))) # [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] #[1,] 1 2 3 4 8 5 3 11 #[2,] 9 5 2 0 0 0 0 0 
+2
source

Source: https://habr.com/ru/post/1480839/


All Articles