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

Reputation: 574

Adding dataframe name to plot with lapply in R?

I tried hard to add the dataframe's name to plot for plots more than one.

Here is sample data.

df<-structure(list(d1 = structure(list(lists..1.. = c(43L, 64L, 55L, 
52L, 56L, 68L, 33L, 15L, 10L, 62L, 3L, 51L, 16L, 80L, 48L, 6L, 
58L, 38L, 91L, 76L, 95L, 32L, 17L, 45L)), .Names = "lists..1..", row.names = c(NA, 
-24L), class = "data.frame"), d2 = structure(list(lists..2.. = c(100L, 
67L, 84L, 93L, 8L, 22L, 38L, 71L, 76L, 99L, 31L, 18L, 5L, 48L, 
25L, 68L, 94L, 81L, 36L, 45L, 56L, 34L, 74L, 44L)), .Names = "lists..2..", row.names = c(NA, 
-24L), class = "data.frame")), .Names = c("d1", "d2"))

And sample function:

fun<- function(x) {
h1<-max(x)
h2<-min(x)

  plot(h1, h2)
  pname <-lapply(x, function(x) (paste(unique(sub("\\.\\d+$", "", names(x))))))
  mtext(pname,side=3,padj=2)
  }

I used

out<-lapply(df, fun)

plot

As you see, title is character(0) for both dataframe. But what I want is see d1 and d2 separately for each plot.

Upvotes: 3

Views: 260

Answers (3)

zx8754
zx8754

Reputation: 56149

We could move the lapply into the function:

fun <- function(x){
  lapply(seq_along(x), function(i){
    h1 <- max(x[[ i ]])
    h2 <- min(x[[ i ]])
    plot(h1, h2)
    mtext(names(x)[ i ], side = 3, padj = 2)  
  })
}

# then pass the list of dataframes to function
fun(df)

Upvotes: 0

Clemsang
Clemsang

Reputation: 5481

You can use parent.frame that get names in the environment:

fun<- function(x) {
  h1<-max(x)
  h2<-min(x)

  plot(h1, h2)
  pname <- lapply(x, function(x) (paste(unique(sub("\\.\\d+$", "", parent.frame()$i[])))))
  mtext(pname,side=3,padj=2)
}

out<-lapply(df, fun)

Upvotes: 2

Ronak Shah
Ronak Shah

Reputation: 388907

lapply doesn't pass names of the list. One way would be to use Map and pass names separately.

fun <- function(x, y) {
   h1<-max(x)
   h2<-min(x)
   plot(h1, h2)
   pname <- sub("\\.\\d+$", "", y)
   mtext(pname,side=3,padj=2)
}

Map(fun, df, names(df))

enter image description here

The same can also be achieved with imap from purrr

purrr::imap(df, fun)

If you still want to use lapply, you can pass the index subset the data in the function

fun<- function(x) {
   h1<-max(df[[x]])
   h2<-min(df[[x]])
   plot(h1, h2)
   pname <- sub("\\.\\d+$", "", names(df)[x])
   mtext(pname,side=3,padj=2)
}

lapply(seq_along(df), fun)

Upvotes: 4

Related Questions