我有一个向量,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
系列函数来做到这一点?
答案 0 :(得分:1)
rep( resp, times = counts)
使用基本功能rep