我的原始data.frame看起来像这样:
df1
Group Variable Text
AB a Sentence1
AB b Sentence2
AB c Sentence3
XY d Sentence4
XY e Sentence5
XY f Sentence6
ZW g Sentence7
ZW h Sentence8
ZW i Sentence9
现在我需要像这样重新安排:
df2
AB XY ZW Text1 Text2 Text3
a d g Sentence1 Sentence4 Sentence7
b e h Sentence2 Sentence5 Sentence8
c f i Sentence3 Sentence6 Sentence9
P.S:我的输出data.frame看起来像这样的原因是我稍后会连接每行的Text1-Text3列。但是我在R之外做。
非常感谢您的帮助!
df1&的代码DF2:
df1 <- data.frame(Group = c("AB", "AB", "AB", "XY", "XY", "XY", "ZW", "ZW", "ZW"),
Variable = c("a", "b", "c", "d", "e", "f", "g", "h", "i"),
Text = c("Sentence1", "Sentence2", "Sentence3", "Sentence4", "Sentence5", "Sentence6", "Sentence7", "Sentence8", "Sentence9"))
df2 <- data.frame(AB = c("a", "b", "c"),
XY = c("d", "e", "f"),
ZW = c("g", "h", "i"),
Text1 = c("Sentence1", "Sentence2", "Sentence3"),
Text2 = c("Sentence4", "Sentence5", "Sentence6"),
Text3 = c("Sentence7", "Sentence8", "Sentence9"))
答案 0 :(得分:1)
我们可以通过在dcast
data.table
中的value.var
来执行此操作
library(data.table)
dcast(setDT(df1), rowid(Group) ~ Group, value.var = c('Variable', 'Text'))[, Group := NULL][]