r-For循环遍历数据帧中模式匹配的列并生成ggplot



使用下面的示例数据,我想遍历数据框架中的列以生成ggplot,但我很难获得正确的逻辑(我是R的新手(。我只想用短语";百分比;在他们身上。

这是我在一列上生成单个ggplot的例子:

ggwatched10percent = ggplot(data = df1, aes(x=Duration, y=watched10percent))
ggwatched10percent + geom_point(aes(colour=factor(Content))) + ggtitle("Duration / viewed10percent Viewed")
ggsave(file.path('graphs', 'watched10percent.pdf'))

我正在寻找一个for循环,考虑到下面的数据,它将遍历watched10%、watched50%和watched100%列(在每次迭代中,始终使用Duration和Content列(。

给定的列将用作y值。我还需要将给定的列用作ggsave中的文件名,用于图表标题,也可能用作图形的变量(例如ggwatched10ercent(——尽管我很乐意为此增加一个数字。

样本数据:

Content <- c('Part1','Part2','Part3')
Duration <- c(102, 205, 167)
watched10percent <- c('76','72','81')
watched50percent <- c('54','58','72')
watched100percent <- c('37','31','68')
df1 <- data.frame(Content, Duration, watched10percent, watched50percent, watched100percent)

编辑-我已经删除了提供的数据样本。。。我得到的错误是因为我的数据没有聚合,但一旦聚合,提供的答案就完美地发挥了作用。

这里有一种方法。

如果您希望使用for循环,您可以查看包含"的列名;百分比";。

y轴可以引用.data[[wp]]从列名中提取适当的数据。

您可以通过多种方式将列名集成到标题中。最终的ggsave也可以使用.pdf文件的列名。

library(ggplot2)
for (wp in names(df1)[grepl("percent", names(df1))]) {
ggplot(data = df1, aes(x = Duration, y = .data[[wp]])) +
geom_point(aes(colour = factor(Content))) + 
ggtitle(paste("Duration /", wp, "Viewed"))

ggsave(file.path('graphs', paste0(wp, '.pdf')))
}

最新更新