r - ggplot 和 dplyr 以及列名作为字符串

标签 r string ggplot2 dplyr

我想通过 dplyrggplot 使用字符串形式的列名来处理数据框。这是我的代码

library(ggplot2)
library(dplyr)
my_df <- data.frame(var_1 = sample(c('a', 'b', 'c'), 1000, replace = TRUE),
                    var_2 = sample(c('d', 'e', 'f'), 1000, replace = TRUE))

name_list = c('var_1', 'var_2')

for(el in name_list){
  pdf(paste(el, '.pdf', sep =''))
    test <- my_df %>% group_by(el) %>% summarize(count = n())
    ggplot(data = test, aes(x = el, y = count)) + geom_bar(stat='identity')
  dev.off()
}

上面的代码显然是行不通的。所以我尝试了不同的东西,比如 UQas.nameUQ 创建带有额外引号的列,而 ggplot 无法使用 aes_string 理解它。有什么建议吗?

我可以使用 for (el in names(my_df)) 进行过滤,但更喜欢使用字符串。

更新 以下是我收到的详细消息/错误:

for(el in name_list){
  pdf(paste(el, '.pdf', sep =''))
    test <- my_df %>% group_by(!!el) %>% summarize(count = n())
    ggplot(data = test, aes_string(x = el, y = 'count')) + geom_bar(stat='identity')
  dev.off()
}

以上代码生成空文件。

for(el in name_list){
  pdf(paste(el, '.pdf', sep =''))
    test <- my_df %>% group_by(UQ(el)) %>% summarize(count = n())
    ggplot(data = test, aes_string(x = el, y = 'count')) + geom_bar(stat='identity')
  dev.off()
}

上面的代码也会生成空文件

for(el in name_list){
  pdf(paste(el, '.pdf', sep =''))
    test <- my_df %>% group_by(as.name(el)) %>% summarize(count = n())
    ggplot(data = test, aes_string(x = el, y = 'count')) + geom_bar(stat='identity')
  dev.off()
}

产生

Error in mutate_impl(.data, dots) : 
  Column `as.name(el)` is of unsupported type symbol

最佳答案

您需要UQ(或!!)名称/符号。例如

for(el in name_list){
  pdf(paste(el, '.pdf', sep =''))
  test <- my_df %>% group_by(UQ(as.name(el))) %>% summarize(count = n())
  print(ggplot(data = test, aes_string(x = el, y = 'count')) + geom_bar(stat='identity'))
  dev.off()
}

关于r - ggplot 和 dplyr 以及列名作为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46372691/

相关文章:

r - 如何在 R studio 中分层比较两个 ggplot(换句话说,有两个图相互重叠并通过我的输入进行比较)?

r - ggplot2 命名空间问题

r - 在R中成对计算两列之间的差异

R:通过选择某些行来生成频率表

python - 字符串预处理

java - 正则表达式括号或数字行首

java - 编写一个方法,多次打印出字符串 "Name"

r - 将错误栏添加到 ggplot 时出错

r - facet_wrap 与来自 GGally 的 ggparcoord()

r - 警告 : replacing previous import ‘head’ when loading ‘utils’ in R