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

R 在数据帧中,重复X列中的单词,重复次数如y列所示,r,R,我有一列是单词(x),一列是数字(y)。我想创建第三列(z),其中单词重复的次数如第y列所示 示例数据: x <- c("one", "two", "three") y <- c(1, 2, 3) df <- data.frame(x, y) x我们可以使用strep with(df, strrep(x, y)) 它给出了一个没有空格的输出,但是如果我们需要一个空格,那么在“x”中的字符串末尾粘贴一个空格,执行strep并用trimws df$z <- with

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

示例数据:

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

x我们可以使用
strep

with(df, strrep(x, y))
它给出了一个没有空格的输出,但是如果我们需要一个空格,那么
在“x”中的字符串末尾粘贴一个空格,执行
strep
并用
trimws

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