【发布时间】:2020-09-27 14:35:23
【问题描述】:
我有
>head(p)
study treatment response
1 14 SSA 3
2 1 SSTR 4
3 14 SSA 3
4 6 SSTR 3
5 10 SSA 4
我想计算每个study 的response,然后添加bind_rows 以获得所有response。
所以我有
p %>% as_tibble() %>%
mutate(nystudie=as.character(study),
best.resp =as.factor(response)) %>%
bind_rows(., mutate(., nystudie="All")) %>%
count(nystudie, best.resp)
产量
# A tibble: 27 x 3
nystudie best.resp n
<chr> <fct> <int>
1 1 3 2
2 1 4 3
3 10 4 2
4 11 3 1
但是,我想在 ggplot 中使用 tibblestratified 为 p$treatment 做一个 facet_wrap,ala + facet_wrap(., treatment) + ...
因此,我正在寻求有关如何优化脚本的帮助,以便预期的输出如下所示:
# A tibble: 27 x 3
nystudie best.resp n treatment
<chr> <fct> <int> <fct>
1 1 3 2 "SSTR"
2 1 4 3 "SSTR"
3 10 4 2 "SSTR"
4 11 3 1 "SSA"
数据
p <- structure(list(study = structure(c(13L, 2L, 1L, 4L, 4L, 8L, 1L,
3L, 1L, 4L, 12L, 1L, 13L, 1L, 8L, 1L, 6L, 4L, 9L, 13L, 14L, 1L,
8L, 12L, 5L, 11L, 13L, 8L, 4L, 8L, 9L, 4L, 11L, 1L, 4L, 9L, 4L,
15L, 11L, 9L, 12L, 2L, 11L, 6L, 12L, 12L, 8L, 10L, 4L, 2L), .Label = c("1",
"2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13",
"14", "15", "22"), class = "factor"), treatment = structure(c(2L,
1L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 1L,
1L, 2L, 2L, 2L, 1L, 2L, 2L, 1L, 2L, 2L, 2L, 1L, 2L, 2L, 1L, 2L,
1L, 1L, 2L, 1L, 2L, 2L, 2L, 2L, 1L, 2L, 1L, 2L, 2L, 2L, 2L, 1L,
1L), .Label = c("SSTR", "SSA"), class = "factor"), response = c("1",
"3", "4", "3", "3", "3", "3", "3", "3", "3", "4", "4", "4", "3",
"2", "4", "4", "4", "4", "4", "4", "4", "1", "3", "3", "4", "4",
"1", "4", "1", "4", "4", "4", "3", "3", "2", "3", "4", "4", "2",
"3", "3", "3", "4", "3", "4", "2", "4", "4", "3")), row.names = c(NA,
-50L), class = "data.frame")
【问题讨论】:
-
你可以试试这个代码,看看它是否是你要找的:
p %>% mutate(nystudie=as.character(study), best.resp =as.factor(response)) %>% bind_rows(., mutate(., nystudie="All")) %>% group_by(nystudie,best.resp) %>% summarise(N=n(),Val=unique(treatment)) -
您好,亲爱的。非常感谢你的问题很酷:)
-
@Duck - 谢谢,您的回答很有帮助。感谢您的所有帮助。
标签: r dataframe ggplot2 plot dplyr