2017-12-30 17 views
1

単語(x)と数字(y)の列が1つあります。私は、単語が列yで示された回数繰り返される第3列(z)を作成したいと思います。列内のデータフレーム繰り返しワードX列に示された回数X

例データ:私は試してみました

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) 

答えて

3

我々はstrrep

with(df, strrep(x, y)) 
を使用することができます

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

これは好ましい最終結果であり、スペースのない出力が得られますが、私たちは「X」の文字列の末尾にスペース、そしてpasteスペースが必要な場合は、strrepを行うとして最後に余分なスペースを削除

trimws

df$z <- with(df, trimws(strrep(paste(x, ' '), y))) 
df$z 
#[1] "one"     "two two"   "three three three" 
関連する問題