7

我需要从包含大部分重复数据的 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

有任何想法吗?

4

3 回答 3

7

使用这个reshape2包很简单:

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
于 2013-02-22T20:36:45.670 回答
6

使用plyransstrsplit你可以做这样的事情:

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)) })
于 2013-02-22T20:11:24.890 回答
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')
于 2013-02-22T20:18:40.203 回答