我有以下问题:
dd <- structure(list(group_members = structure(c(6L, 6L, 1L, 1L, 2L, 2L, 3L, 3L, 4L, 4L, 5L, 5L),
.Label = c("1", "2", "3", "4", "5", ">6"), class = "factor"), Test_A = c("negative", "positive",
"negatiu", "positive", "negatiu", "positive", "negatiu", "positive", "negatiu", "positive", "negatiu", "positive"), cases = c(58L, 2L, 14781L, 3525L, 7867L, 415L, 4113L, 72L, 2054L, 10L, 347L, 2L)), row.names = c(NA, -12L), groups = structure(list(group_members = structure(1:6, .Label = c("1", "2", "3", "4", "5", ">6"), class = "factor"), .rows = structure(list( 3:4, 5:6, 7:8, 9:10, 11:12, 1:2), ptype = integer(0), class = c("vctrs_list_of", "vctrs_vctr", "list"))), row.names = c(NA, 6L), class = c("tbl_df", "tbl", "data.frame"), .drop = TRUE), class = c("grouped_df", "tbl_df", "tbl", "data.frame"))
这是小标题
> dd
# A tibble: 12 x 3
# Groups: group_members [6]
group_members Test_A cases
<fct> <chr> <int>
1 >6 negative 58
2 >6 positive 2
3 1 negatiu 14781
4 1 positive 3525
5 2 negatiu 7867
6 2 positive 415
7 3 negatiu 4113
8 3 positive 72
9 4 negatiu 2054
10 4 positive 10
11 5 negatiu 347
12 5 positive 2
我想要每个小组的相对丰富。例如,对于“ group_members> 6”,我有58个否定案例和2个肯定案例。我想获得一个新的专栏,如下所示:
对于第6组的示例:“频率= 58/60 = 0.96和“频率= 2/60 = 0.04”“
> dd
# A tibble: 12 x 3
# Groups: group_members [6]
group_members Test_A cases frequency
<fct> <chr> <int>
1 >6 negative 58 0.96
2 >6 positive 2 0.004
.....
谢谢你的帮助。
dd %>%
group_by(group_members) %>%
mutate(frequency = cases / sum(cases))
给出:
# A tibble: 12 x 4
# Groups: group_members [6]
group_members Test_A cases frequency
<fct> <chr> <int> <dbl>
1 >6 negative 58 0.967
2 >6 positive 2 0.0333
3 1 negatiu 14781 0.807
4 1 positive 3525 0.193
5 2 negatiu 7867 0.950
6 2 positive 415 0.0501
7 3 negatiu 4113 0.983
8 3 positive 72 0.0172
9 4 negatiu 2054 0.995
10 4 positive 10 0.00484
11 5 negatiu 347 0.994
12 5 positive 2 0.00573
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句