简体   繁体   English

根据基础 R 中另一个向量的值生成重复值的向量

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

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 (eg for batch = 1, the 1st value of alpha should be repeated the number of times 1 appears).我想创建一个向量,比如alphai ,它重复alpha的第 i 个元素,它以给定值batch出现的次数(例如,对于 batch = 1,alpha 的第一个值应该重复的次数1 出现)。 The desired output should look like this:所需的 output 应如下所示:

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!请提供基础 R 唯一解决方案,谢谢!

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 (ie 1,3,4,5,etc.)我希望提供的代码可以在批处理情况下工作,其中批处理可以是非递增序列或不连续的序列(即 1、3、4、5 等)

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 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

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.R中,索引从 1 开始。因此,如果我们指定多个 1,它会从第一个 Z4757FE07FD492A8BE0EA6A760D683DDE6 中提取 'alpha' object 中的元素。 Note that an index of 0 will be skipped as there is no element请注意,索引 0 将被跳过,因为没有元素

alpha[batch]

Another way would be to use rep with table .另一种方法是将reptable一起使用。

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 .batch不遵循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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM