在R中重新格式化表格

时间:2015-09-14 17:27:35

标签: r reshape

我有一个表格如下(具有相同ID的不同行将具有相同的性别和年龄值,但不同的类别和子类别值):

  ID product.category sub.category gender   age
1  1             food      chicken      M young
2  1          kitchen       napkin      M young
3  1             food        steak      M young
4  2       electronic        phone      F   mid
5  3            cloth        shirt      M   old
6  3          kitchen         bowl      M   old
7  4             alch         beer      F young

通过组合具有相同ID的不同行,我想改进表格如下:

  ID product.category1 sub.category1 product.category2 sub.category2 product.category3 sub.category3 gender   age
1  1              food       chicken           kitchen        napkin              food         steak      M young
2  2        electronic         phone              null          null              null          null      F   mid
3  3             cloth         shirt           kitchen          bowl              null          null      M   old
4  4              alch          beer              null          null              null          null      F young

我怎样才能在R?

中这样做 #

新数据集:文本变量实际上是备注的文本列

text    Category    Subcategory variable1   variable2   variable3   variable4   date
aaaaa   c1  s11 v1  N   RETAIL  Y   2014-01
aaaaa   c2  s22 v1  N   LEASE   Y   2014-01
aaaaa   c3  s31 v1  N   LEASE   Y   2014-01
bbbbb   c1  s12 v2  N   LEASE   Y   2014-01
ccccc   c2  s21 v1  N   LEASE   Y   2014-01
ddddd   c2  s21 v1  N   RETAIL  Y   2014-01
ddddd   c3  s31 v1  N   LEASE   Y   2014-01
eeeee   c1  s11 v1  N   RETAIL  Y   2014-01
fffff   c2  s21 v2  U   RETAIL  Y   2014-01

谢谢

3 个答案:

答案 0 :(得分:6)

我们使用包SELECT CASE WHEN NULL > 0 THEN 'NULL > 0 = true' ELSE 'NULL > 0 = false' END, CASE WHEN LEN(NULL) > 0 THEN 'LEN(NULL) = true' ELSE 'LEN(NULL) = false' END, CASE WHEN LEN('') > 0 THEN 'LEN('''') > 0 = true' ELSE 'LEN('''') > 0 = false' END, CASE WHEN LEN(' ') > 0 THEN 'LEN('' '') > 0 = true' ELSE 'LEN('' '') > 0 = false' END, CASE WHEN LEN(' test ') > 0 THEN 'LEN('' test '') > 0 = true' ELSE 'LEN('' test '') > 0 = false' END meltdcast的组合。

reshape2

我们首先按产品类别和子类别融合原始数据框。接下来使用dplyr,我们按id列和产品列(默认情况下现在称为“变量”)进行分组,并创建一个名为library(dplyr) library(reshape2) m2 <- melt(df, c("ID", "gender", "age")) %>% group_by(ID, variable) %>% mutate(variable2 = paste0(variable, seq_along(value))) newdf <- dcast(m2[!names(m2) %in% "variable"], ...~variable2, value.var="value", fill="null") 的新列。这只是类别标题的粘贴和观察的运行计数。

现在我们有了一个新列,我们可以将数据传播出去。我们使用variable2在新的variable2列上“宽”。还有一个名为dcast的论点,我们设置等于fill告诉dcast填充缺失值的内容。

下面我们根据所需的输出重新排序列。即使它很小,但值得注意的是诀窍。创建交织序列很有意思。我们的输出按字母顺序排列(“p1”,“p2”,“p3”,“s1”,“s2”,“s3”)。我们想要一个将它们编织在一起的序列。挑战是获得类似(1,4,2,5,3,6)的东西。所以我们使用:

"null"
好吧,好吧?我们利用rbind在按行输入值的同时逐列展开的事实。在我们的例子中,编写c(rbind(1:3, 4:6)) [1] 1 4 2 5 3 6 无能为力,因为数据中可能会有更多产品。但我们知道有两个标题“产品类别”和“子子类别”。我们将1:3的唯一值除以2,然后使用它。

variable2

<强>更新

使用提供的新数据集,相同的代码结构将与新列名称一起使用。

n <- nrow(unique(m2[,"variable2"]))
newdf[c(1:3,(c(rbind(1:(n/2), (n/2+1):n))+3))]
#   ID gender   age product.category1 sub.category1 product.category2
# 1  1      M young              food       chicken           kitchen
# 2  2      F   mid        electronic         phone              null
# 3  3      M   old             cloth         shirt           kitchen
# 4  4      F young              alch          beer              null
#   sub.category2 product.category3 sub.category3
# 1        napkin              food         steak
# 2          null              null          null
# 3          bowl              null          null
# 4          null              null          null

答案 1 :(得分:5)

data.table dcast 您可以使用reshape2或data.table包中的dcast

library(data.table)
setDT(DT)

DT[, obsno := 1:.N, by=ID]
res <- dcast(DT, ID+gender+age~obsno, value.var=c("product.category","sub.category"))

给出了

   ID gender   age product.category_1 product.category_2 product.category_3 sub.category_1 sub.category_2 sub.category_3
1:  1      M young               food            kitchen               food        chicken         napkin          steak
2:  2      F   mid         electronic                 NA                 NA          phone             NA             NA
3:  3      M   old              cloth            kitchen                 NA          shirt           bowl             NA
4:  4      F young               alch                 NA                 NA           beer             NA             NA

要按所需顺序查看列,您可以执行类似

的操作
res[, c(1:3,4,7,5,8,6,9), with=FALSE]

tidyr套餐可能采用类似的方法(尽管它不会被称为&#34; dcast&#34;)。

我建议坚持使用长格式(你原来的)进行任何分析。除了浏览数据之外,您正在寻找的这种广泛格式非常麻烦。

第二个例子对于OP的第二个例子,我会做

DT2[, obsno := 1:.N, by=text]
dcast(DT2, ...~obsno, value.var=c("Category", "Subcategory"))

从@ PierreLafortune的回答中复制...~技巧。结果是

    text variable1 variable2 variable3 variable4    date Category_1 Category_2 Category_3 Subcategory_1 Subcategory_2 Subcategory_3
1: aaaaa        v1         N     LEASE         Y 2014-01         NA         c2         c3            NA           s22           s31
2: aaaaa        v1         N    RETAIL         Y 2014-01         c1         NA         NA           s11            NA            NA
3: bbbbb        v2         N     LEASE         Y 2014-01         c1         NA         NA           s12            NA            NA
4: ccccc        v1         N     LEASE         Y 2014-01         c2         NA         NA           s21            NA            NA
5: ddddd        v1         N     LEASE         Y 2014-01         NA         c3         NA            NA           s31            NA
6: ddddd        v1         N    RETAIL         Y 2014-01         c2         NA         NA           s21            NA            NA
7: eeeee        v1         N    RETAIL         Y 2014-01         c1         NA         NA           s11            NA            NA
8: fffff        v2         U    RETAIL         Y 2014-01         c2         NA         NA           s21            NA            NA

答案 2 :(得分:4)

dplyr&amp;的替代方案tidyr

newdf <- df %>% gather(variable, value, product.category, sub.category) %>%
  group_by(ID, variable) %>%
  mutate(variable2 = paste0(variable, seq_along(value))) %>%
  ungroup() %>%
  select(-variable) %>%
  spread(variable2 , value)

给出:

> newdf
Source: local data frame [4 x 9]

     ID gender    age product.category1 product.category2 product.category3 sub.category1 sub.category2 sub.category3
  (int) (fctr) (fctr)             (chr)             (chr)             (chr)         (chr)         (chr)         (chr)
1     1      M  young              food           kitchen              food       chicken        napkin         steak
2     2      F    mid        electronic                NA                NA         phone            NA            NA
3     3      M    old             cloth           kitchen                NA         shirt          bowl            NA
4     4      F  young              alch                NA                NA          beer            NA            NA

在第二个示例数据集上也可以这样做:

newdat <- dat %>% gather(variable, value, Category, Subcategory) %>%
  group_by(text, variable) %>%
  mutate(var2 = paste0(variable, seq_along(value))) %>%
  ungroup() %>%
  select(-variable) %>%
  spread(var2 , value)

给出:

> newdat
Source: local data frame [8 x 12]

    text variable1 variable2 variable3 variable4    date Category1 Category2 Category3 Subcategory1 Subcategory2 Subcategory3
  (fctr)    (fctr)    (fctr)    (fctr)    (fctr)  (fctr)     (chr)     (chr)     (chr)        (chr)        (chr)        (chr)
1  aaaaa        v1         N     LEASE         Y 2014-01        NA        c2        c3           NA          s22          s31
2  aaaaa        v1         N    RETAIL         Y 2014-01        c1        NA        NA          s11           NA           NA
3  bbbbb        v2         N     LEASE         Y 2014-01        c1        NA        NA          s12           NA           NA
4  ccccc        v1         N     LEASE         Y 2014-01        c2        NA        NA          s21           NA           NA
5  ddddd        v1         N     LEASE         Y 2014-01        NA        c3        NA           NA          s31           NA
6  ddddd        v1         N    RETAIL         Y 2014-01        c2        NA        NA          s21           NA           NA
7  eeeee        v1         N    RETAIL         Y 2014-01        c1        NA        NA          s11           NA           NA
8  fffff        v2         U    RETAIL         Y 2014-01        c2        NA        NA          s21           NA           NA