使用计数的命名向量创建重复向量序列

时间:2019-08-29 08:56:22

标签: r

我有一个向量,resp包含名称,counts包含计数。我想创建一个向量,该向量重复resp中的元素并重复counts中的元素,然后将其分配给变量feedback

resp <- c("yes", "no", "maybe")
counts <- c(5, 10, 10)

所需的输出

> feedback
 [1] "yes"    "yes"    "yes"    "yes"    "yes"    "no"     "no"     "no"     "no"     "no"     "no"     "no"    
[13] "no"     "no"     "no"     "may be" "may be" "may be" "may be" "may be" "may be" "may be" "may be" "may be"
[25] "may be"

我可以使用for循环执行以下操作:


resp <- c("yes", "no", "maybe")
counts <- c(5, 10, 10)
names(counts) <- resp

feedback <- c()

for (i in 1:length(resp)){
  feedback <- c(feedback, rep(resp[i], counts[i]))
}

是否可以使用apply系列函数来做到这一点?

1 个答案:

答案 0 :(得分:1)

rep( resp, times = counts)

使用基本功能rep