Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use lapply to plot data in a list and use names of list elements as plot titles [duplicate]

Tags:

regex

plot

r

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 plot each list element:

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

However, I want to include the name of each list element as plot title (main). For my example data, the title of each graph would be a,b and c respectively. First thing, is that I have a gsub rule that given comp.surv$a, I return a :

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

Which is good. However I cannot embed this result into my lapply statement above. Any ideas?

In the mean time I have tried getting round this by creating a function this 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 plot each sub-variable of comp.surv, but all the titles are blank.

Can anyone recommend if I am going down the right track?

like image 658
brucezepplin Avatar asked Jun 12 '15 11:06

brucezepplin


2 Answers

One possibility would be to loop over the names of the list:

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

Or slightly more verbose, loop over the list indices:

lapply(seq_along(comp.surv), function(x) plot(comp.surv[[x]], main = names(comp.surv)[x]))
like image 146
Henrik Avatar answered Oct 13 '22 13:10

Henrik


Is that what you want?

ns=names(comp.surv)
lapply(ns, function(x) plot(comp.surv[[x]], main=x,ylab="y"))
like image 26
Robert Avatar answered Oct 13 '22 12:10

Robert