将数据从3行重组为1

时间:2013-02-22 19:58:42

标签: r csv reshape2

我需要重新组织包含大多数重复数据的csv文件中的数据。我在数据框中将数据导入到R中,但我遇到以下问题:

ID   Language  Author   Keyword
12   eng       Rob      COLOR=Red
12   eng       Rob      SIZE=Large
12   eng       Rob      DD=1
15   eng       John     COLOR=Red
15   eng       John     SIZE=Medium
15   eng       John     DD=2

我需要做的是将其转换为一行,每个关键字都在一个单独的列中

ID   Language  Author  COLOR  SIZE      DD
12   eng       Rob     Red    Large     1

有什么想法吗?

3 个答案:

答案 0 :(得分:7)

使用reshape2包这很简单:

Gary's answer

中定义tt
library("reshape2")

tt <- cbind(tt, colsplit(tt$Keyword, "=", c("Name", "Value")))
tt_new <- dcast(tt, ID + Language + Author ~ Name, value.var="Value")

给出了

> tt_new
  ID Language Author COLOR DD   SIZE
1 12      eng    Rob   Red  1  Large
2 15      eng   John   Red  2 Medium

答案 1 :(得分:6)

使用plyr ans strsplit您可以执行以下操作:

library(plyr)
res <- ddply(dat,.(ID,Language,Author),function(x){
        unlist(sapply(strsplit(x$Keyword,'='),'[',2))
})

colnames(res)[4:6] <- c('COLOR','SIZE','DD')

 ID Language Author COLOR   SIZE DD
1 12      eng    Rob   Red  Large  1
2 15      eng   John   Red Medium  2

编辑:这是一个解决@Brian关注问题的概括:

res <- ddply(dat,.(ID,Language,Author), function(x){
             kv <- strsplit(x$Keyword, '=')
             setNames(sapply(kv, `[`, 2),
                      sapply(kv, `[`, 1)) })

答案 2 :(得分:1)

使用reshape2

尝试此操作
tt <- read.table(header=T,text='ID   Language  Author   Keyword
 12   eng       Rob      COLOR=Red
 12   eng       Rob      SIZE=Large
 12   eng       Rob      DD=1
 15   eng       John     COLOR=Red
 15   eng       John     SIZE=Medium
 15   eng       John     DD=2')

tt$Keyword <- as.character(tt$Keyword)

tt <- transform(tt, key_val = lapply(tt$Keyword,function(x) strsplit(x,'=')[[1]][2]),
 key_var = lapply(tt$Keyword,function(x) strsplit(x,'=')[[1]][1]))

tt_new <- dcast (tt, ID + Language + Author ~ key_var, value.var='key_val')