【问题标题】:Using lapply to generate multiple graphs, iterate over the list to title the graphs not working使用 lapply 生成多个图表,遍历列表以标题不工作的图表
【发布时间】:2020-05-16 22:46:00
【问题描述】:

我创建了以下代码以从列表“hemi_split”中成功生成我想要的图形,但是当我尝试为图形命名时会生成以下错误

`"hemi_split[i] 中的错误:无效的下标类型'list'"

这里是代码

graphs <- lapply(hemi_split, function(i){ 
  ggplot(data=i, aes(x=type, y=shoot.mass))+
    geom_point()+
    facet_wrap(.~host)+ 
    theme_minimal()+
    labs(title=names(hemi_split[i]))
         })

这是我要为每个图表命名的列表元素的名称

names(hemi_split)
 [1] "CADE" "CAFO" "CAHI" "CALE" "CAMI" "CARU" "CAWI" "COPI" "REEL" "TRER" "TRVE"

感谢您的帮助!

【问题讨论】:

    标签: r loops split lapply


    【解决方案1】:

    如果你确实在名单上,你忘记了名字,你可以试试:

    graphs <- lapply(names(hemi_split), function(i){ 
      ggplot(data=hemi_split[[i]], aes(x=type, y=shoot.mass))+
        geom_point()+
        facet_wrap(.~host)+ 
        theme_minimal()+
        labs(title=i))
             })
    

    【讨论】:

      【解决方案2】:

      使用purrrimap,您可以访问数据和名称。

      graphs <- purrr::imap(hemi_split, ~{ 
                   ggplot(data=.x, aes(x=type, y=shoot.mass))+
                   geom_point()+
                   facet_wrap(.~host)+ 
                   theme_minimal()+
                   labs(title=.y)
                 })
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-07-21
        • 2021-12-05
        • 2023-03-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-05-18
        • 2022-01-13
        相关资源
        最近更新 更多