问题:如何从现有数据集中生成新数据集。
我有一个非平凡的数据,下面我提供了简化的版本。数据是关于个人的,我的性别,原籍国以及他们从事的部门和职业。
我想:1.创建一个列,其中所有sector X职业组合都存储。2.对于每个这样的部门X职业,计算有多少女性,有多少男性以及来自每个国家的男性。
id <- c(1,2,3,4,5)
occupation <- c(11,12,11,12,11)
sector <- c("a", "b", "c", "a", "b")
sex <- c(0,1,0,1,0)
country <- c(1,2,3,2,1)
data <- data.frame(id, occupation, sector, sex, country)
id occupation sector sex country
1 11 a 0 1
2 12 b 1 2
3 11 a 0 3
4 12 a 1 2
5 11 b 0 1
这就是我想要获得的:
occXsector sex0 sex1 country1 country2 country3
1 11-a 0 2 1 0 1
2 11-b 0 1 1 0 0
3 12-a 1 0 0 1 0
4 12-b 1 0 0 1 0
任何帮助将不胜感激!
您需要清理输入/输出,也就是说,您显示的预期输出从您给出的输入中没有意义,但请尝试一下
library(dplyr)
library(tidyr)
data %>%
mutate(occXsector = paste(occupation, sector, sep="-")) %>%
gather(key, value, sex, country) %>%
mutate(newvalue = paste(key, value, sep="")) %>%
group_by(occXsector) %>%
count(newvalue) %>%
spread(newvalue, n, fill=0)
# A tibble: 5 x 6
# Groups: occXsector [5]
occXsector country1 country2 country3 sex0 sex1
* <chr> <dbl> <dbl> <dbl> <dbl> <dbl>
1 11-a 1 0 0 1 0
2 11-b 1 0 0 1 0
3 11-c 0 0 1 1 0
4 12-a 0 1 0 0 1
5 12-b 0 1 0 0 1