Creating variables from factor records in R

拟墨画扇 提交于 2019-12-03 22:44:41

问题


I am kind of lost, I have a data frame that looks like this:

tract   ageClass    count
    1      [0-4]       71
    2      [0-4]      192
    3      [0-4]       81
    1      [5-8]        9
    2      [5-8]       86
    3      [5-8]       42

I would like to have this result:

tract   [0-4]   [5-8]
    1      71       9
    2     192      86
    3      81      42

I have been looking in the internet for a solution for quite some time but so far nothing... any idea?

Many thanks!


回答1:


Three possible options I can think of (assuming your data set called df)

xtabs(count ~ tract + ageClass, df) 
#       ageClass
# tract [0-4] [5-8]
#     1    71     9
#     2   192    86
#     3    81    42

Or

library(reshape2)
dcast(df, tract ~ ageClass, value.var = "count") 
#   tract [0-4] [5-8]
# 1     1    71     9
# 2     2   192    86
# 3     3    81    42

Or

library(tidyr)
spread(df, ageClass, count)
#   tract [0-4] [5-8]
# 1     1    71     9
# 2     2   192    86
# 3     3    81    42



回答2:


ageClass <- c("[0-4]", "[5-8]")
ageClassDF <- lapply(ageClass, function(x) dx[which(dx$ageClass==x), ])

ageClassDF <- Reduce(function(...) merge(..., by = "tract.1", all = TRUE), ageClassDF )


来源:https://stackoverflow.com/questions/29118709/creating-variables-from-factor-records-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!