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

plyransを使用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)) })
于 2013-02-22T20:11:24.890 に答える