在数据帧中,如列y中所​​示,在列X中重复单词X次

时间:2017-12-30 08:23:27

标签: r

我有一列带有单词(x),一列带有数字(y)。我想创建第三列(z),其中单词重复y列中指示的次数。

示例数据:

 x <- c("one", "two", "three")
 y <- c(1, 2, 3)
 df <- data.frame(x, y)

这是首选的最终结果:

 z <- c("one", "two two", "three three three")
 df <- data.frame(x, y, z)

       x y                 z
 1   one 1               one
 2   two 2           two two
 3 three 3 three three three

我试过了:

df$z <- rep(df$x, df$y)

1 个答案:

答案 0 :(得分:3)

我们可以使用strrep

with(df, strrep(x, y))

给出了没有空格的输出,但是如果我们需要一个空格,那么paste在'x'中字符串末尾的空格,执行strrep并删除额外的空格结束trimws

df$z <- with(df, trimws(strrep(paste(x, ' '), y)))
df$z
#[1] "one"                 "two  two"            "three  three  three"