使用lapply将变量名称用作情节标题 [英] Use variable name as plot title with lapply

查看:283
本文介绍了使用lapply将变量名称用作情节标题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在1-3个图之间显示,并且我希望图的标题基于所使用的变量名.

I need to display between 1-3 graphs, and I want the titles of the graphs to be based on the variable name that used.

我可以按照下面的方法来工作:

I can get this to work how I want below:

library(grid)
library(ggplot2)
library(gridExtra)

a1 <- sample(1:100)
a2 <- sample(1:100)
a3 <- sample(1:100)

make_graph <- function(x, y=deparse(substitute(x))){
        time <- 1:100
        dfp <- data.frame(time, x)
        ggplot(dfp, aes(x=time, y=x)) + geom_point() +
        ggtitle(y)
}

g1 <- make_graph(a1)
g2 <- make_graph(a2)
g3 <- make_graph(a3)
grid.arrange(g1,g2,g3)

但是如果只有1个或2个样本(即只有a1或a1& a2),当我需要包括条件语句时,这将变得效率低下.

But this becomes inefficient when I need to include conditional statements if there are only 1 or 2 samples (i.e. only a1, or a1 & a2).

除了正确的标题外,我所有工作都可以在下面进行:

I got everything to work below, with the exception of the correct titles:

library(grid)
library(ggplot2)
library(gridExtra)

a1 <- sample(1:100)
a2 <- sample(1:100)
a3 <- sample(1:100)

sample_list <- paste0("a", seq_len(3))

make_graph <- function(x, y=deparse(substitute(x))){
        time <- 1:100
        dfp <- data.frame(time, x)
        ggplot(dfp, aes(x=time, y=x)) + geom_point() +
        ggtitle(y)
}

graphs_list <- lapply(mget(sample_list), make_graph)
do.call("grid.arrange", graphs_list)

使用上面的代码,我获得了正确的功能,但是make_graph()中的deparse()似乎有一些问题,我认为这是因为用lapply调用了.因此,代替了最初示例中的标题("a1","a2","a3"),我得到的是"X [[1L]]","X [[2L]]","X [[ 3L]].

With the above code I get the correct functionality, but deparse() in make_graph() seems to have some issues, I assume due to being called with lapply. So instead of the titles I had in the initial example ("a1", "a2", "a3"), I instead get "X[[1L]]", "X[[2L]]", "X[[3L]]".

我也尝试过更改lapply函数,但这只会给我列表中的第一个标题":

I've also tried altering the lapply function, but this only gives me the first "title" in the list:

sample_list <- paste0("a", seq_len(3))

make_graph <- function(x, y){
        time <- 1:100
        dfp <- data.frame(time, x)
        ggplot(dfp, aes(x=time, y=x)) + geom_point() +
        ggtitle(y)
}

graphs_list <- lapply(mget(sample_list), make_graph, y=sample_list)
do.call("grid.arrange", graphs_list)

我不确定要完成此处要执行的操作的最佳方法. 感谢您的帮助.

I'm not sure of the best approach to accomplish what I'm trying to do here. Thanks for any help.

推荐答案

对于那些来自lapply的变量名,您是正确的.因此,在这种情况下,deparse策略不是一个好方法.但是,由于您非常容易传递标题,因此可以只使用Map而不是lapply.

You are right about those variable names coming from lapply. So that deparse strategy isn't a good one in that case. But since you made it super easy to pass along the title, you can just use Map rather than lapply.

graphs_list <- Map(make_graph, mget(sample_list), sample_list)
do.call("grid.arrange", graphs_list)

这给出了预期的结果.

这篇关于使用lapply将变量名称用作情节标题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆