在R中操纵因子和类别

时间:2017-11-16 18:14:47

标签: r data-manipulation spread dcast

所以我有一个数据集我试图操纵,我似乎无法找到正确的方法来做到这一点。我看着使用dcast和传播,但不知道如何得到正确的操作。

所以我有类似的东西:

ID var1 var2 var3 category
--------------------------
1  x    x    x     a
1  x    x    x     b
1  x    x    x     b
2  y    y    y     a
2  y    y    y     b
2  y    y    y     c
3  z    z    z     b 
3  z    z    z     b
3  z    z    z     c

我觉得它看起来像这样:

ID var1 var2 var3  a  b  c 
--------------------------------
1  x    x    x     1  1  0 
2  y    y    y     1  1  1
3  z    z    z     0  1  1  

简单示例数据

ID <- c(1,1,1,2,2,2,3,3,3)
var1 <- c('x','x','x','y','y','y','z','z','z')
var2 <- c('x','x','x','y','y','y','z','z','z')
var3 <- c('x','x','x','y','y','y','z','z','z')
category <- c('a','b','b','a','b','c','b','b','c')

dat <- data.frame(ID,var1,var2,var3,category)

2 个答案:

答案 0 :(得分:1)

ID <- c(1,1,1,2,2,2,3,3,3)
var1 <- c("x","x","x","y","y","y","z","z","z")
var2 <- c("x","x","x","y","y","y","z","z","z")
var3 <- c("x","x","x","y","y","y","z","z","z")
category <- c("a","b","b","a","b","c","b","b","c")

dat <- data.frame(ID,var1,var2,var3,category)

library(tidyr)
library(dplyr)

dat %>%
  distinct() %>%                   # get distinct rows
  mutate(value = 1) %>%            # create a counter
  spread(category, value, fill=0)  # reshape dataset

#   ID var1 var2 var3 a b c
# 1  1    x    x    x 1 1 0
# 2  2    y    y    y 1 1 1
# 3  3    z    z    z 0 1 1

答案 1 :(得分:0)

由于问题标有dcast,我觉得有必要使用dcast()发布简明的解决方案。

OP没有解释如何计算宽格式的列。从预期结果来看,OP似乎对计算出现次数感兴趣,而是表示每个唯一组合的存在与否(1 / 0代替TRUE / FALSE)。

因此,重塑操作中只包含唯一的行。 length()仍然用作聚合函数,因为它根据请求填充空单元格为0.

library(reshape2)
dcast(unique(dat), ... ~ category, length)
  ID var1 var2 var3 a b c
1  1    x    x    x 1 1 0
2  2    y    y    y 1 1 1
3  3    z    z    z 0 1 1