问题
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 ;-)
回答1:
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)
回答2:
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 (i.e., 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.
回答3:
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
}
来源:https://stackoverflow.com/questions/16729853/plot-titles-in-r-using-sapply