2016-11-11 70 views
-2

Education_table如何映射来自表格中的数据R

正如您在图像上看到的那样。 表显示教育(因素)和education_num(int)之间的关系。 简单地说,幼儿园是1作为education_num 1至4是2作为education_num 等等 博士是16作为education_num。 问题是我想制作一张映射教育和education_num的新表格。 即, 它看起来像

学龄前1

1s4-第四2

博士16

我想我需要使用切()或添加选项在表中(),但我不知道如何做到这一点。

感谢

+0

使用'dput请提供可重复的例子()'。将指针悬停在“r”标签上以获取更多信息。 –

+0

1)可重复的例子(2)研究努力 – vagabond

回答

1

我假设你有原始数据帧的人口普查,在那样的形式:

> df <- data.frame(education=c("pre","pre","1st-4th","5th-6th","1st-4th"),education_num=c(1,1,2,3,2)) 

> df 
    education education_num 
1  pre    1 
2  pre    1 
3 1st-4th    2 
4 5th-6th    3 
5 1st-4th    2 

所以,你可以得到独特的价值观:

> unique(df) 
    education education_num 
1  pre    1 
3 1st-4th    2 
4 5th-6th    3 

,或者如果你有其他数据帧中的列,您可以使用:

library(dplyr) 

df %>% 
    group_by(education) %>% 
    summarise(education_num=unique(education_num)) %>% 
    arrange(education_num) 

# A tibble: 3 x 2 
    education education_num 
    <fctr>   <dbl> 
1  pre    1 
2 1st-4th    2 
3 5th-6th    3 

编辑

如果你想从该表进行改造,就可以使用以下命令:

df <- data.frame(education=c("pre","pre","1st-4th","5th-6th","1st-4th"),education_num=c(1,1,2,3,2)) 

kk <- table(df$education,df$education_num) 

> kk 

      1 2 3 
    1st-4th 0 2 0 
    5th-6th 0 0 1 
    pre  2 0 0 

dfx <- data.frame(edu=row.names(kk)) %>% 
     mutate(edu_num=sapply(edu, function(x) which(kk[x,]>0))) 

> dfx 
     edu edu_num 
1 1st-4th  2 
2 5th-6th  3 
3  pre  1 
+0

首先,谢谢你的回答。 那么,我问的不是如何获得每个值,但 如何从上表转换为您在答案上作出的表 –

+0

我编辑我的答案,检查出来。 – OmaymaS

+0

这可以帮助我很多。自从我知道如何实施其他方式以来 但我只想知道这项工作是否有捷径。 非常感谢 –