gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 02:18:01 24 4
gpt4 key购买 nike

我想通过 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com