Home > Back-end >  Automate input for new vector
Automate input for new vector

Time:08-30

I was wondering if you had any idea what R code I could use to automate my process.

I would like to repeat "chunks" of an initial vector (Vec1). I divide the vector in groups of 4 values and repeat each group 5 times. Currently, with my bad technique, each time I add a new experiment to the analysis I have to manually create a vector to indicate which chunk I would like to repeat next. In the end I put the vector corresponding to each experiment together to get my desired output.

Vec1 <- A simple numeric vector that grows in size for each new experiment. Each new experiment extends the vector by 4 additional values.

Exp1 <- rep(Vec1 [1:4], times=5)
Exp2 <- rep(Vec1 [5:8], times=5)
Exp3 <- rep(Vec1 [9:12], times=5)


NewVector<- c(Exp1, Exp2, Exp3)

Could I use a trick to automate it?

Many thanks for the help,

Best regards,

Edouard M.

CodePudding user response:

I don't know about "automate". You could write a function that takes the values 1:4 and adds multiples of 4 to it.

add_exp <- function(values = 1:4, n = 0) {
  rep(values, 5)   4 * n
}

Then add_exp() gives:

 [1] 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4

And add_exp(n = 1) gives:

 [1] 5 6 7 8 5 6 7 8 5 6 7 8 5 6 7 8 5 6 7 8

So you could get NewVector using:

NewVector<- c(add_exp(), add_exp(n = 1), add_exp(n = 2))

Or if you wanted to use lapply to supply the values of n:

NewVector <- unlist(lapply(0:2, function(x) add_exp(n = x)))

CodePudding user response:

Using sequence:

n <- 3L # number of experiments
v <- 4L # length of vector added for each experiment
r <- 5L # number of replications

sequence(rep(v, n*r), rep(seq(1, n*v, v), each = r))
#>  [1]  1  2  3  4  1  2  3  4  1  2  3  4  1  2  3  4  1  2  3  4  5  6  7  8  5
#> [26]  6  7  8  5  6  7  8  5  6  7  8  5  6  7  8  9 10 11 12  9 10 11 12  9 10
#> [51] 11 12  9 10 11 12  9 10 11 12
  • Related