我有一個包含分組變數的資料框。使用創建資料框串列很簡單,group_split但是我想轉身并制作一個使用構面一次將這 5 個分組的圖。為了重現性,我將使用mtcars
ldf <- mtcars %>%
group_split(carb)
現在我對如何做相當于:
ldf[1:3] %>%
bind_rows( .id = "column_label") %>%
ggplot(aes(x = disp, y = hp))
geom_line()
facet_wrap(carb ~ ., ncol = 1)
ldf[4:6] %>%
bind_rows( .id = "column_label") %>%
ggplot(aes(x = disp, y = hp))
geom_line()
facet_wrap(carb ~ ., ncol = 1)
我不必手動使用 [1:3]、[4:6] 等對串列進行切片,只需提供像 3 或 5 這樣的 n 值。
偏好 tidyverse 解決方案第二選擇基數 r。先感謝您
uj5u.com熱心網友回復:
根據評論,這是我的建議,沒有group_split:
n_per_group = 3
mtcars %>%
mutate(
carb_grp = as.integer(factor(carb)),
plot_grp = (carb_grp - 1) %/% n_per_group
) %>%
group_by(plot_grp) %>%
group_map(
~ggplot(., aes(x = disp, y = hp))
geom_line()
facet_wrap(carb ~ ., ncol = 1)
)
一般來說,我發現我可能想做的大部分事情group_split都可以用它group_map來代替,而且有時將資料放在一起也有好處——比如易于重組,就像這個例子一樣。
uj5u.com熱心網友回復:
我認為您應該首先查看不需要拆分然后取消拆分的解決方案......但是如果您堅持使用它,那么您可以將它們分組,如下所示:
ggs <- split(ldf, (seq_along(ldf)-1) %/% 3) %>%
lapply(function(z) {
bind_rows(z, .id = "column_label") %>%
ggplot(aes(x = disp, y = hp))
geom_line()
facet_wrap(carb ~ ., ncol = 1)
})
(產生list2 個gg物件中的一個。)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/418382.html
標籤:
上一篇:R按標簽差異聚合
