简体   繁体   中英

Add values to a vector to make a consecutive vector in R

I have several vectors that look like this:

v1 <- c(1,2,4)
v2 <- c(3,5,8)
v3 <- c(4)

This is just a small sample of them. I'm trying to figure out a way to add values to each of them to make them all consecutive vectors. So that at the end, they look like this:

v1 <- c(1,2,3,4)
v2 <- c(1,2,3,4,5,6,7,8)
v3 <- c(1,2,3,4)

So "3" is added to the first vector, "1","2","4","6","7" is added to the second and so forth. I have several hundred vectors that look like this so I'm trying to figure out a solution that would scale/be automated.

You can use seq and max

  seq(max(v1))

For multiple vectors, we can loop

 lapply(mget(paste0('v',1:3)), function(x) seq(max(x)))
 #$v1
 #[1] 1 2 3 4

 #$v2
 #[1] 1 2 3 4 5 6 7 8

 #$v3
 #[1] 1 2 3 4

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