在 R 中投射数据框

Casting data frame in R

我的数据如下所示:

dput(head(dat, 10)
structure(list(Label = c("Nuclear Blast", "Nuclear Blast", "Nuclear Blast", 
                     "Nuclear Blast", "Nuclear Blast", "Nuclear Blast", "Nuclear Blast", 
                     "Metal Blade Records", "Metal Blade Records", "Metal Blade Records"
), Info = c("Germany", " +49 7162 9280-0 ", "active", " N/A ", 
        "1987", "\n\t\t\t\t\t\t\t\t\tAnstalt Records,\t\t\t\t\t\t\t\t\tArctic Serenades,\t\t\t\t\t\t\t\t\tCannibalised Serial Killer,\t\t\t\t\t\t\t\t\tDeathwish Office,\t\t\t\t\t\t\t\t\tEpica,\t\t\t\t\t\t\t\t\tGore Records,\t\t\t\t\t\t\t\t\tGrind Syndicate Media,\t\t\t\t\t\t\t\t\tNuclear Blast America,\t\t\t\t\t\t\t\t\tNuclear Blast Brasil,\t\t\t\t\t\t\t\t\tNuclear Blast Entertainment,\t\t\t\t\t\t\t\t\tRadiation Records,\t\t\t\t\t\t\t\t\tRevolution Entertainment\t\t\t\t\t      ", 
        "Yes", " 5737 Kanan Road #143\n\nAgoura Hills, California 91301 ", 
        "United States", " N/A ")), .Names = c("Label", "Info"), row.names = c(NA, 
                                                                               10L), class = "data.frame")

如何重塑它,使其看起来像下面这样?

  Label                 Var1            Var2            Var3      Var4   Var5    Var6                Var7
1 Nuclear Blast        Germany      +49 7162 9280-0     active    N/A    1987    Anstalt Records...  Yes 
2 Metal Blade Records  5737 Kanan.. United States       N/A

我意识到每个标签的行数不一致,但我可以稍后在 excel 或 R 中清理它。

试试这个:

library(data.table)
setDT(dat)

dat[, Col:= paste0('Var', 1:.N), by='Label']

dat = dcast.data.table(dat, Label ~ Col, value.var='Info')

这是一个使用dplyr/tidyr

的选项
library(dplyr)
library(tidyr)
dat %>% 
    group_by(Label) %>% #group by Label
    mutate(Col = paste0("Var", row_number())) %>% #create a sequence column
    spread(Col, Info) #spread to wide format