R:熔化数据以将 3 列折叠为 1 列,并将每行加倍

R: melt data to collapse 3 columns into 1 column and double that for each row

我有如下数据:

 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 行,前三行是前 3 行的重复。

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

 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,但我不确定如何实现。

非常感谢任何见解。

使用 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