【问题标题】:R: melt data to collapse 3 columns into 1 column and double that for each rowR:融合数据以将 3 列折叠为 1 列,并将每行的数据加倍
【发布时间】:2016-10-04 23:30:40
【问题描述】:

我有如下数据:

 df1
 id count white_v pink_v others_v 
 1  1     0.4      0.5   0.6
 1  2     0.5      0.5   0.747
 1  3     0.87     0.57  0.87
 2  1     1.5      2.5   1.2 
 ....

我想重塑数据,使其与以下格式的另一个数据框兼容:

 df2
  id count white pink
  1    1   1      0 
  1    1   0      1
  1    1   0      0
  1    1   1      0
  1    1   0      1
  1    1   0      0

所以基本上,我想将粉色、白色和其他颜色的值从 df1 附加到 df2,但 df2 的格式是每种颜色都是虚拟编码的(粉色和白色的 0,0 表示该列用于其他)。对于每个客户的每次购买,df2 有 6 行,前三行是前三行的重复。

我想要实现的是如下的数据框:

 df3
 id count white pink   v
  1  1    1     0      0.4 -> indicates the value of white_v for id 1,count1
  1  1    0     1      0.5 -> indicates the value of pink_v for id 1, count1
  1  1    0     0      0.6 -> indicates the value of others_v for id 1, count1
  1  1    1     0      0.4 -> indicates the value of white_v for id 1,count1
  1  1    0     1      0.5 -> similarly as above
  1  1    0     0      0.6  

我需要遍历每个人和他们的每次购买计数。我曾考虑过使用循环,但在如何使用 i 来索引 df1 和 df2 的行方面陷入困境。然后我也考虑过使用 reshape ,但我不确定如何实现这一点。

非常感谢任何见解。

【问题讨论】:

  • 在我看来,(df2 的格式)是个坏主意。最好有一个包含“白色”、“粉红色”或“其他”的因子列,而不是这些多余的 0/1 变量。

标签: r reshape2


【解决方案1】:

使用 tidyr 和 dplyr,

library(tidyverse)

        # gather colors into long key and value columns
df1 %>% gather(color, v, white_v:others_v) %>% 
    # drop "_v" endings; use regex if you prefer
    separate(color, 'color', extra = 'drop') %>% 
    # add a vector of 1s to spread
    mutate(n = 1) %>%    # more robust: count(id, count, color, v)
    # spread labels and 1s to wide form
    spread(color, n, fill = 0)

##    id count     v others pink white
## 1   1     1 0.400      0    0     1
## 2   1     1 0.500      0    1     0
## 3   1     1 0.600      1    0     0
## 4   1     2 0.500      0    1     1
## 5   1     2 0.747      1    0     0
## 6   1     3 0.570      0    1     0
## 7   1     3 0.870      1    0     1
## 8   2     1 1.200      1    0     0
## 9   2     1 1.500      0    0     1
## 10  2     1 2.500      0    1     0

【讨论】:

  • 但是我想要的结果是我得到前三行之后,我会重复三行一次然后继续..df3的格式是我想要的
  • 手动重复以使其对齐是一个非常非常糟糕的主意。请改用联接。正如弗兰克所提到的,长篇大论可能更容易。
  • 另一个有趣的选择:df1 %>% gather(color, v, white_v:others_v) %>% model.matrix( ~ . - 1, data = .) %>% as.data.frame()
猜你喜欢
  • 1970-01-01
  • 2021-03-18
  • 1970-01-01
  • 2023-02-21
  • 1970-01-01
  • 2020-09-29
  • 1970-01-01
  • 1970-01-01
  • 2020-06-05
相关资源
最近更新 更多