请考虑下面的最小示例:我将来自两个实验A和B的观察结果合并为dplyr tibble。llim和ulim定义了每组中可观测值的下限和上限。
library(dplyr)
name <- factor (c (rep('A', 400),
rep('B', 260)
)
)
obs <- c (sample(-23:28, 400, replace = TRUE),
sample(-15:39, 260, replace = TRUE)
)
llim <- c (rep(-23, 400),
rep(-15, 260)
)
ulim <- c (rep(28, 400),
rep(39, 260)
)
tib1 <- tibble (name, obs, llim, ulim)
tib1
# A tibble: 660 x 4
name obs llim ulim
<fct> <int> <dbl> <dbl>
1 A 22 -23 28
2 A -5 -23 28
3 A 2 -23 28
4 A 9 -23 28
5 A -1 -23 28
6 A -21 -23 28
7 A 13 -23 28
8 A 0 -23 28
9 A 8 -23 28
10 A -11 -23 28
# … with 650 more rows接下来,我计算每个组的可观察值的直方图。只要我使用hist()的默认参数,就可以很好地工作。
tib1 %>% group_by(name) %>%
summarise (counts = hist(obs, plot = FALSE)$counts)
`summarise()` has grouped output by 'name'. You can override using the `.groups` argument.
# A tibble: 22 x 2
# Groups: name [2]
name counts
<fct> <int>
1 A 26
2 A 44
3 A 39
4 A 32
5 A 42
6 A 34
7 A 44
8 A 41
9 A 39
10 A 37
# … with 12 more rows现在,我想使用tibble中存储的更多特定于组的参数来调整这些直方图,例如llim和ulim。然而,这似乎不起作用:
tib1 %>% group_by(name) %>%
summarise (counts = hist (obs,
breaks = seq (llim,
ulim,
by = 1
),
plot = FALSE
)$counts
)
Error: Problem with `summarise()` input `counts`.
✖ 'from' must be of length 1
ℹ Input `counts` is `hist(obs, breaks = seq(llim, ulim, by = 1), plot = FALSE)$counts`.
ℹ The error occurred in group 1: name = "A".
Run `rlang::last_error()` to see where the error occurred.是否有一种方法可以将列llim和ulim中的值传递给hist()函数?还是有不同的问题?这个错误信息有点神秘...
您的帮助将不胜感激!
发布于 2021-04-03 21:30:32
将llim和ulim的长度减少到1(例如使用max()或min())可以做到这一点:
tib1 %>% group_by(name, llim, ulim) %>%
summarise (counts = hist (obs,
breaks = seq (max(llim),
max(ulim),
by = 1
),
plot = FALSE
)$counts
)
# A tibble: 105 x 4
# Groups: name, llim, ulim [2]
name llim ulim counts
<fct> <dbl> <dbl> <int>
1 A -23 28 9
2 A -23 28 9
3 A -23 28 8
4 A -23 28 7
5 A -23 28 5
6 A -23 28 8
7 A -23 28 14
8 A -23 28 10
9 A -23 28 9
10 A -23 28 9
# … with 95 more rows因此,错误消息最终是有意义的。
发布于 2021-04-03 21:27:02
这给出了按组name划分的obs直方图
library(ggplot2)
ggplot(tib1, aes(x = obs)) +
geom_histogram(aes(color = name, fill = name),
position = "identity", bins = 30, alpha = 0.4) +
scale_color_manual(values = c("blue", "red")) +
scale_fill_manual(values = c("blue", "red"))

https://stackoverflow.com/questions/66931212
复制相似问题