[英]Create a dataframe with a list of plots using map in R
我正在嘗試創建一個數據圖,該數據圖具有作為列表嵌入到數據框中的圖,以便可以查看由行代表的每個模型的兩個圖形。
這是一個最小的例子,顯示了我的困境
foo <- function(x) {
list(
plots = list(qplot(1), qplot(2)),
bar = 'bar',
x = x
)
}
not_df <- purrr::map(1:5, foo) # Create 5 items using foo above
map(not_df, length) # 5 items, each of length 3.
# Doesn't work
df <- purrr::map_df(1:5, foo)
as_data_frame(not_df)
bind_rows(not_df)
map和bind_rows均失敗,並顯示Error: incompatible sizes (2 != 1)
做這個:
do.call(rbind,not_df)
這是一個tidyverse
方法,但我修改了您的示例。 讓我知道這是否是您的目標:
df = data.frame(x=1:5, a=11:15, b=21:25)
df = df %>% group_by(x) %>%
mutate(p1 = list(ggplot(., aes(a, b)) + geom_point()),
p2 = list(ggplot(., aes(a, b)) + geom_point())) %>%
ungroup %>%
nest(p1, p2, .key=plots)
df
# A tibble: 5 × 4 xab plots 1 1 11 21 <tibble [1 × 2]> 2 2 12 22 <tibble [1 × 2]> 3 3 13 23 <tibble [1 × 2]> 4 4 14 24 <tibble [1 × 2]> 5 5 15 25 <tibble [1 × 2]>
如果你的函數輸出tibble
而不是(從tidyverse /包tibble) list
,您可以使用map_df
直接得到你想要的輸出。
我發現tribble
函數在這里更有用,因為如果不使用plots
列的嵌套列表,那么通過tibble
可以回收單個值。
有tribble
foo2 <- function(x) {
tibble::tribble(
~plots, ~bar, ~x,
list(qplot(1), qplot(2)), 'bar', x
)
}
purrr::map_df(1:5, foo2)
# A tibble: 5 × 3
plots bar x
<list> <chr> <int>
1 <list [2]> bar 1
2 <list [2]> bar 2
3 <list [2]> bar 3
4 <list [2]> bar 4
5 <list [2]> bar 5
帶有tibble
和plots
的嵌套列表
foo <- function(x) {
tibble::tibble(
plots = list(list(qplot(1), qplot(2))),
bar = 'bar',
x = x
)
}
purrr::map_df(1:5, foo)
# A tibble: 5 × 3
plots bar x
<list> <chr> <int>
1 <list [2]> bar 1
2 <list [2]> bar 2
3 <list [2]> bar 3
4 <list [2]> bar 4
5 <list [2]> bar 5
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.