【发布时间】:2020-12-26 03:33:47
【问题描述】:
这是对上一篇帖子here 的后续问题。
我从@akrun 那里得到了一组关于我的玩具问题的很好的答案,但是当我阅读答案时,我意识到它实际上还不适用于现实生活中的问题。这个问题的说明仍然是正确的::
之前:
之后:
进一步的挑战是“grp”和“治疗”变量只是我所描述的级别,因为这些是需要传播控制的地方。事实上,还有四个与组处于同一级别的额外分组变量,每个变量都有自己的一组阳性和阴性对照。
因此,此问题的解决方案不能是识别所有阴性/阳性对照并将它们附加到每个组。解决方案需要在考虑分组的情况下执行,然后在所有组中适当地传播。由于 dplyr 似乎非常适合这种方法,我认为这是要走的路,但我有点卡在中间。对我来说,这建议了一个 purrr 解决方案,但除了 reduce() 之外,我根本没有使用 purrr。或者可能是group_by() %>% nest %>% ... %>% unnest 的路要走?p>
library(tidyverse)
data_propagated_controls <- data %>%
# \\ group the data by all the grouping variables
# \\ exclude the 'treatment' variables
group_by(var1, var2, var3) %>%
# \\ split into individual dataframes
group_split() %>%
# \\ for each list item propagate controls
# \\ similar as the problem described below
# \\ steps to run in pseudocode
identify and extract controls
append controls to each treatment
add a column to distinguish treatment/controls
join all treatments/controls by rbind
# \\ reassemble the dataframe from the list
# \\ reduce with rbind or full_join should work
reduce(split, rbind)
上一篇文章中的问题说明:
librar(ggplot)
before <- structure(list(group = c("grp1", "grp1", "grp1", "grp1",
"grp2", "grp2", "grp2", "grp2", "grp3", "grp3", "grp3", "grp3",
"neg", "neg", "pos", "pos"), treatment = c("A", "B", "C",
"D", "A", "B", "C", "D", "A", "B", "C", "D", "none", "none",
"none", "none"), value = c(3L, 5L, 7L, 9L, 2L, 4L, 6L, 8L, 3L,
4L, 6L, 9L, 12L, 10L, 1L, 2L)), class = "data.frame", row.names = c(NA, -16L))
ggplot(data = before, aes(x=treatment, y=value)) + geom_boxplot() + facet_wrap (~group)
after <- structure(list(group = c("grp1", "grp1", "grp1", "grp1", "grp1", "grp1",
"grp1", "grp1", "grp2", "grp2", "grp2", "grp2", "grp2", "grp2",
"grp2", "grp2", "grp3", "grp3", "grp3", "grp3", "grp3", "grp3",
"grp3", "grp3"), treatment = c("A", "B", "C", "D", "neg", "neg",
"pos", "pos", "A", "B", "C", "D", "neg", "neg", "pos", "pos",
"A", "B", "C", "D", "neg", "neg", "pos", "pos"), value = c(3L,
5L, 7L, 9L, 12L, 10L, 1L, 2L, 2L, 4L, 6L, 8L, 12L, 10L, 1L, 2L,
3L, 4L, 6L, 9L, 12L, 10L, 1L, 2L)), class = "data.frame", row.names = c(NA, -24L))
ggplot(data = after, aes(x=treatment, y=value)) + geom_boxplot() + facet_wrap (~group)
【问题讨论】:
-
想了想,我想我可以通过多种方式来解决这个问题。要么我只是在
group_by和group_split之后获取列表,然后通过 lapply 运行一些附加功能,以按照概述添加到数据集。或者,我可以通过lapply在拆分列表中的分组数据帧上生成我喜欢的图,甚至无需修改数据集。