簡體   English   中英

使用R中的map創建帶有繪圖列表的數據框

[英]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

帶有tibbleplots的嵌套列表

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM