Hüsamettin Tayşi
Hüsamettin Tayşi

Reputation: 574

How to use list elements as plot title in r?

I have this kind of data:

d<- list(d1 = list(`1979` = 3.8234619080332, `1980` = 3.94835997755299, 
    `1981` = 4.40780893307071), d2 = list(`1979` = 3.78682062013644, 
    `1980` = 3.89720895853959, `1981` = 4.35137469930167))

I am trying to plot my data and I want to use the list names d1 and d2 as plot titles.

I have tried this function with lapply;

fun1<-function(x) {
  y<-x
  x<-unlist(x)
  plot(ecdf(x), main=deparse(substitute(y)))
  }

lapply(d, fun1)

What I got are:

enter image description here

enter image description here

But I want to see d1 for the first plot and d2 for the second plot as the main title name instead of "list(d1 = list(1979 = 3.823461...."

Upvotes: 1

Views: 777

Answers (3)

Ronak Shah
Ronak Shah

Reputation: 388907

Using purrr::imap -

fun1<-function(x, y) {
  plot(ecdf(unlist(x)), main=y)
}

purrr::imap(d, fun1)

Upvotes: 0

jay.sf
jay.sf

Reputation: 72683

You could include the lapply() in your function and use the names().

fun1 <- function(d) {
  nm <- names(d)
  lapply(nm, function(i) plot(ecdf(unlist(d[[i]])), main=i))
}

op <- par(mfrow=c(1, 2))
fun1(d)
par(op)

enter image description here

Upvotes: 0

stefan
stefan

Reputation: 124013

You could use mapply to loop over both d and names(d) to pass the name of the list element to your function:

d<- list(d1 = list(`1979` = 3.8234619080332, `1980` = 3.94835997755299, 
                   `1981` = 4.40780893307071), d2 = list(`1979` = 3.78682062013644, 
                                                         `1980` = 3.89720895853959, `1981` = 4.35137469930167))

fun1<-function(x, y) {
  plot(ecdf(unlist(x)), main=y)
}

mapply(fun1, d, names(d))

Upvotes: 3

Related Questions