Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate a vector of repeated values based on the values of another vector in base R

Tags:

r

vector

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
like image 286
latlio Avatar asked Sep 01 '25 02:09

latlio


2 Answers

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]
like image 94
akrun Avatar answered Sep 02 '25 18:09

akrun


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
like image 36
Ronak Shah Avatar answered Sep 02 '25 16:09

Ronak Shah