【发布时间】:2018-08-26 03:24:23
【问题描述】:
我的数据显示了某些群体中具有不同教育程度的人的百分比:
df <- data_frame(group = c("A", "B"),
no.highschool = c(20, 10),
high.school = c(70,40),
college = c(10, 40),
graduate = c(0,10))
df
# A tibble: 2 x 5
group no.highschool high.school college graduate
<chr> <dbl> <dbl> <dbl> <dbl>
1 A 20. 70. 10. 0.
2 B 10. 40. 40. 10.
例如,在 A 组中,70% 的人受过高中教育。
我想生成 4 个变量,让我知道每组中受教育程度低于 4 级的人的比例(例如,lessthan_no.highschool、lessthan_high.school 等)。
想要的 df 是:
desired.df <- data.frame(group = c("A", "B"),
no.highschool = c(20, 10),
high.school = c(70,40),
college = c(10, 40),
graduate = c(0,10),
lessthan_no.highschool = c(0,0),
lessthan_high.school = c(20, 10),
lessthan_college = c(90, 50),
lessthan_graduate = c(100, 90))
在我的实际数据中,我有很多群体和更多的教育水平。当然,我可以一次执行一个变量,但是我如何使用tidyverse 工具以编程方式(并且优雅地)执行此操作?
我会首先在map() 中执行mutate_at() 之类的操作,但我遇到的问题是每个新变量的总和变量列表都不同。您可以将新变量列表及其对应变量作为两个列表相加到pmap(),但如何简洁地生成第二个列表并不明显。想知道是否有某种嵌套解决方案...
【问题讨论】:
-
没有低于 no.highschool 的级别,因此 lessthan_no.highschool 将始终为 0。
-
在
desired.df中有变量less.than.hs。不应该是no.highschool吗? -
不确定您的意思?
-
@lost Gregor 击败了我,在您想要的结果中,您重复输入的变量,因此它们的名称应该相同。其中之一不是。我认为这是一个错字。哦,我错过了关于
tidyverse的部分,所以我正忙于编写基本的 R 方式。会感兴趣吗? -
这是一个错字,抱歉。固定。