【问题标题】:For loop to iterate through pattern matched column in data frame and produce ggplotFor循环遍历数据框中的模式匹配列并生成ggplot
【发布时间】:2020-12-02 10:37:37
【问题描述】:

使用下面的示例数据,我想遍历我的数据框中的列以生成 ggplot,但我正在努力使逻辑正确(我是 R 新手)。我只想遍历其中包含短语“percent”的列。

这是我在一个列上生成单个 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 循环,考虑到下面的数据,它将遍历 watch10percent、watched50percent 和 watch100percent 列(在每次迭代中,将始终使用 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)

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

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    这是一种方法。

    如果您希望使用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')))
    }
    

    【讨论】:

    • 感谢您的帮助,不幸的是,我收到以下错误:错误:美学必须是长度 1 或与数据相同 (65):x 运行 rlang::last_error() 以查看错误在哪里发生了。
    • 是后者,我在帖子底部添加了我的实际数据。
    • 我已经添加了我的全套数据 - 我相信原因可能是,内容不是唯一的,因此需要聚合(使用平均值)......这只是我的猜测.持续时间将相同(例如,内容 1.1. 的持续时间始终为 99,但查看的百分比列会有所不同)
    • 我汇总了我的数据,它成功了!感谢您的帮助
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-20
    • 2022-01-20
    • 1970-01-01
    • 1970-01-01
    • 2023-04-10
    相关资源
    最近更新 更多