[英]R: How to apply a function to a data frame to make plots of each subset with a unique factor combination
I would like to understand how the apply functions or anything similar can be used to make plots for several subsets of a data frame. 我想了解应用函数或类似函数如何用于为数据框的几个子集绘制图。 Let's assume I want to use the mtcars data frame and I want to make a plot for each combination of "gear" and "carb".
让我们假设我想使用mtcars数据框,我想为“齿轮”和“碳水化合物”的每个组合制作一个图。
I read here , that one can just write a function and then use lapply to create subsets of a data frame and plots for each of them. 我在这里读到,人们可以编写一个函数,然后使用lapply创建数据框的子集并绘制每个子集的图。 So how could I rewrite this to use lapply or anything similar?
那么我怎么能重写这个来使用lapply或类似的呢?
gg_test = function(data) {
title = paste("gear",data[,"gear"][1],"carb",data[,"carb"][1])
require(ggplot2)
gg1 = ggplot(data, aes(x = mpg, y = cyl, color = disp)) + geom_point() +
ggtitle(title)
print(gg1)
}
for (g in unique(mtcars[,"gear"])){
for(ca in unique(mtcars[,"carb"])){
df_sub = subset(mtcars, gear == g & carb == ca)
gg_test(df_sub)
}
}
You can use split
and interaction
to divide a data.frame into chunks that you can then apply your plot function to: 您可以使用
split
和interaction
将data.frame划分为块,然后可以将绘图函数应用于:
gg_test = function(data) {
title = paste("gear",data[,"gear"][1],"carb",data[,"carb"][1])
require(ggplot2)
ggplot(data, aes(x = mpg, y = cyl, color = disp)) + geom_point() +
ggtitle(title)
}
I modified your plot function to return the plot instead of print it out. 我修改了你的绘图功能以返回绘图而不是打印出来。
plots <- lapply(split(mtcars, interaction(mtcars[,c("gear","carb")]), drop = TRUE), gg_test)
Then I store each plot in another object that can be printed on demand. 然后我将每个绘图存储在另一个可以按需打印的对象中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.