如何添加一个因子级

时间:2018-01-19 10:48:07

标签: r aggregate

我正在与英国data合作。我想添加一个列为genhealth == 1的因子级别agelfted的比例。

到目前为止,我的想法是创建一个单独的列,其中genhealth == 1的数量为agelfted,然后创建一个额外的列,即agelfted个{ genhealth != 1然后简单地将第一个创建的列除以第二个。我真的没有用这个策略做得很远:

oreo$gh<-aggregate(oreo, by=c(subset("genhealth"==1),"agelifted"), FUN = "sum")

Error: unexpected symbol in "oreo$gh<-aggregate(oreo, by=c(subset("genhealth"==1),"agelifted") FUN"

1 个答案:

答案 0 :(得分:1)

dplyr方法:

library(dplyr)

oreo %>%
  group_by(agelfted) %>%                      # for every agelfted value
  mutate(Prop = sum(genhealth == 1)/n()) %>%  # get number of times genhealth = 1 dived by number of total rows
  ungroup()                                   # forget the grouping

# # A tibble: 102,816 x 8
#   sex    yobirth  year genhealth longst_illness   age agelfted  Prop
#   <fct>    <dbl> <dbl>     <dbl>          <dbl> <int>    <dbl> <dbl>
# 1 female    47.0  84.0      1.00           2.00    37     15.0 0.552
# 2 male      24.0  84.0      3.00           1.00    60     14.0 0.456
# 3 female    31.0  84.0      1.00           1.00    53     35.0 0.705
# 4 male      29.0  84.0      1.00           2.00    55     14.0 0.456
# 5 male      39.0  84.0      1.00           2.00    45     18.0 0.706
# 6 female    35.0  84.0      1.00           1.00    49     15.0 0.552
# 7 male      42.0  84.0      1.00           2.00    42     15.0 0.552
# 8 female    43.0  84.0      1.00           1.00    41     16.0 0.646
# 9 male      49.0  84.0      3.00           1.00    35     15.0 0.552
#10 female    40.0  84.0      2.00           2.00    44     15.0 0.552
# # ... with 102,806 more rows