Use lapply to plot data in a list and use the list item names as heading headers

If I have the following list:

comp.surv <- list(a = 1:4, b = c(1, 2, 4, 8), c = c(1, 3, 8, 27))
comp.surv
# $a
# [1] 1 2 3 4
# 
# $b
# [1] 1 2 4 8
# 
# $c
# [1]  1  3  8 27

      

I can use lapply

to build each list item:

lapply(comp.surv, function(x) plot(x))

      

However, I want to include the name of each list item as the plot name ( main

). For my example data, the title of each graph would be a

, b

and c

respectively. The first thing I have a rule gsub

that is set comp.surv$a

, I return a

:

gsub(comp.surv\\$([a-z]+), "\\1", deparse(sustitute((comp.surv$a)))
# "a"

      

It's good. However, I am unable to insert this result into my statement lapply

above. Any ideas?

At the same time, I tried to work around this by creating a this function to include the main parameter:

splot <- function(x){
  plot(x, main = gsub(comp.surv\\$([a-z]+), "\\1" deparse(sustitute((x))))
}

lapply(comp.surv, function(x) splot(x))

      

This will display every comp.surv sub-variable, but all headers are empty.

Can anyone recommend if I'm going the right way?

+3


source to share


2 answers


One possibility would be to names

iterate over the list:

lapply(names(comp.surv), function(x) plot(comp.surv[[x]], main = x))

      



Or, a little more verbose, looping through list indices:

lapply(seq_along(comp.surv), function(x) plot(comp.surv[[x]], main = names(comp.surv)[x]))

      

+6


source


Is this what you want?



ns=names(comp.surv)
lapply(ns, function(x) plot(comp.surv[[x]], main=x,ylab="y"))

      

+1


source







All Articles