我想通过 dplyr
和 ggplot
使用字符串形式的列名来处理数据框。这是我的代码
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()
}
上面的代码显然是行不通的。所以我尝试了不同的东西,比如 UQ
和 as.name
。 UQ
创建带有额外引号的列,而 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/