How to populate new variable with repeated values from vector?

MeC*_*MeC 0 r vector dataframe

I have a vector of values:

    values = c(22, 42, 243)
Run Code Online (Sandbox Code Playgroud)

I have a variable in a dataframe:

    df$variable = 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3
Run Code Online (Sandbox Code Playgroud)

如何在数据帧中的新变量中将值向量中的每个值重复n次,从而得到以下信息:

    df$new_variable = 22, 22, 22, 22, 42, 42, 42, 42, 243, 243, 243, 243
Run Code Online (Sandbox Code Playgroud)

Ist*_*rel 5

最简单的方法是使用sapply

sapply(variable, function(x) df$values[x])
Run Code Online (Sandbox Code Playgroud)

嗯...甚至还有一个更简单的解决方案:

values[df$variable]
Run Code Online (Sandbox Code Playgroud)

  • 很高兴您添加了“值[变量]” (2认同)
  • 在这种情况下,@ markus执行`values [as.integer(factor(df $ variable))]`` (2认同)