Sample data
batch <- c(rep(1,3), rep(2,4), rep(3,5))
batch
[1] 1 1 1 2 2 2 2 3 3 3 3 3
alpha <- c(0.05, 0.04, 0.03)
Problem Statement
I'd like to create a vector, say alphai
, that repeats the ith element of alpha
the number of times it appears in batch
at a given value (e.g. for batch = 1, the 1st value of alpha should be repeated the number of times 1 appears). The desired output should look like this:
alpha
[1] 0.05 0.05 0.05 0.04 0.04 0.04 0.04 0.03 0.03 0.03 0.03 0.03
Please provide base R only solutions, thanks!
EDIT
I would like the code provided to work in batch cases where batch could be either a non-increasing sequencing or a sequence that's non-contiguous (i.e. 1,3,4,5,etc.)
batch2 <- c(rep(1,3), rep(3, 4), rep(4,5))
batch2
[1] 1 1 1 3 3 3 3 4 4 4 4 4
alpha
should still be
[1] 0.05 0.05 0.05 0.04 0.04 0.04 0.04 0.03 0.03 0.03 0.03 0.03
The index can be used for replicating. In R
, indexing starts from 1. So, if we specify multiple 1s, it is extracting the elements in the 'alpha' object from the 1st position multiple times, similarly for other index. Note that an index of 0 will be skipped as there is no element
alpha[batch]
Another way would be to use rep
with table
.
rep(alpha, table(batch))
#[1] 0.05 0.05 0.05 0.04 0.04 0.04 0.04 0.03 0.03 0.03 0.03 0.03
This would be helpful when batch
does not follow the sequence 1:3
. For example,
batch <- rep(10:8, 3:5)
batch
#[1] 10 10 10 9 9 9 9 8 8 8 8 8
rep(alpha, table(batch))
#[1] 0.05 0.05 0.05 0.05 0.05 0.04 0.04 0.04 0.04 0.03 0.03 0.03
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With