Create multiple vector that have same elements but different last elements in R
I want to create multiple vector/ a matrix that looks similar but have different last element For example, I need have a vector c(0,1,1,0) and I want to create a bunch of vectors that look like c(0,1,1,0,5) c(0,1,1,0,10) c(0,1,1,0,15) and so on
How do I do that?
vec <- c(0, 1, 1, 0)
endvec <- c(5, 10, 15) # or seq(5, 15, by = 5) or something else
lapply(endvec, function(a) c(vec, a))
# [[1]]
# [1] 0 1 1 0 5
# [[2]]
# [1] 0 1 1 0 10
# [[3]]
# [1] 0 1 1 0 15
or more briefly:
Map(c, list(vec), endvec)
# [[1]]
# [1] 0 1 1 0 5
# [[2]]
# [1] 0 1 1 0 10
# [[3]]
# [1] 0 1 1 0 15
Here's one way to do it with map
from the purrr
package resulting in a list object holding each of the vectors. This assumes n
is the maximum number you want to reach for the last element.
n <- 1000
base_vec <- c(0, 1, 1, 0)
vec_list <- map(seq(5, n, by=5), ~c(base_vec, ..1))
Sample output:
> vec_list[[1]]
[1] 0 1 1 0 5
> vec_list[[2]]
[1] 0 1 1 0 10
> vec_list[[3]]
[1] 0 1 1 0 15