当前位置:  开发笔记 > 编程语言 > 正文

R - dplyr融合配对数据的交叉

如何解决《R-dplyr融合配对数据的交叉》经验,为你挑选了1个好方法。



1> David Arenbu..:

您可以简单地spread指定数据并运行该table功能dnn

library(dplyr)
library(tidyr)
dta %>%
  spread(sexe, dip14_rec) %>%
  select(-idmen) %>%
  table(., dnn = c("Men", "Women"))
#                 Women
# Men                  No Diploma Primary-Secondary Uni
#    No Diploma                 0                 0   1
#    Primary-Secondary          0                 2   0
#    Uni                        0                 1   1

或类似的 data.table

library(data.table) # V 1.9.6+
dcast(setDT(dta), idmen ~ sexe)[, table(Men = `1`, Women = `2`)]
# Using 'dip14_rec' as value column. Use 'value.var' to override
#                    Women
# Men                 No Diploma Primary-Secondary Uni
#   No Diploma                 0                 0   1
#   Primary-Secondary          0                 2   0
#   Uni                        0                 1   1

数据

dta <- structure(list(idmen = c(110008218L, 110008218L, 110010366L, 
110010366L, 110011567L, 110011567L, 110012163L, 110012163L, 110016580L, 
110016580L), sexe = c(1L, 2L, 1L, 2L, 1L, 2L, 2L, 1L, 2L, 1L), 
    dip14_rec = structure(c(3L, 2L, 3L, 3L, 2L, 2L, 2L, 2L, 3L, 
    1L), .Label = c("No Diploma", "Primary-Secondary", "Uni"), class = "factor")), .Names = c("idmen", 
"sexe", "dip14_rec"), class = "data.frame", row.names = c("1", 
"2", "3", "4", "5", "6", "7", "8", "9", "10"))

推荐阅读
喜生-Da
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有