我想通过处理数据帧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()
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句