R:熔体数据崩溃3列到第1列,双,对于每个行
问题描述:
我有如下所示的数据:R:熔体数据崩溃3列到第1列,双,对于每个行
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的行。然后我也想过使用重塑,但我不知道如何实现这一点。
将不胜感激任何见解。
答
随着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
在我看来,这(DF2的格式)是一个坏主意。更好的方法是在其中添加“白色”,“粉红色”或“其他”的因子列,而不是这些冗余0/1变量。 – Frank