简体   繁体   中英

Plot titles in R using sapply()

I want to make qqnorm plot out of every variable in my data frame using sapply(). This is what I've got so far:

myfun=function(x) {
  c(qqnorm(x),
    qqline(x)
  )
}

sapply(mydata, myfun)

It works, however, I'd like each plot to have the respective variable name in the title of the plot. How is this done?

Thanx a lot ;-)

In this case l_ply is more suitable because you just need to plot and therefore no output is needed. Based on @Henrik answer we have

require(plyr)
myfun <- function(x, data, ...) {
  c(qqnorm(data[[x]], main = names(data)[x], ...),
    qqline(data[[x]])
  )
}

l_ply(seq_len(ncol(swiss)), myfun, data = swiss)

EDIT

If you want to see your graphs, you have many options and one of them is to divide you plotting device and plot each qqplot in one part of the device.

par(mfrow = c(3, 2))
l_ply(seq_len(ncol(swiss)), myfun, data = swiss)

The problem is that when you do it like that the names are not passed over to the function, but only an unnamed list element. You need to slightly alter the function and just hand over the index and then work on the whole object (ie, implicitly doing a for-loop and using an iterator):

data(swiss)

myfun=function(x, data) {
  c(qqnorm(data[[x]], main = colnames(data)[x]),
    qqline(data[[x]])
  )
}

lapply(1:ncol(swiss), myfun, data = swiss)

Also, I changed the function to lapply and use the swiss data set as an example.

Here is a for loop, which is imho the most appropriate loop construct for this.

for (i in seq_along(swiss)) {
  qqnorm(swiss[,i], main = names(swiss)[i])
  qqline(swiss[,i])
  Sys.sleep(3) #to see something and avoid problems in RStudio
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM