要构建for循环,如何在count()命令中使用变量名?

时间:2017-02-03 17:36:51

标签: r loops count

library(dplyr)
library(plyr) 

df = data.frame(x = sample(c("Large","Medium", "Small"), 10, replace = TRUE), y = sample(c("Yes","No"), 10, replace = TRUE), z = sample(c("High","Low"), 10, replace = TRUE) )

df %>% 
count('x') %>% 
ggplot(aes(x,freq)) +  
geom_bar(stat = "identity") -> a

df %>% 
count('y') %>% 
ggplot(aes(y,freq)) +  
geom_bar(stat = "identity") -> b

df %>% 
count('z') %>% 
ggplot(aes(z,freq)) +  
geom_bar(stat = "identity") -> c

grid.arrange(a,b,c, ncol=3, nrow =1)

我没有两次编写上面的代码,而是想构建一个如下所示的循环:

for (val in names(df)) {
df %>% 
count(get(val)) %>% 
ggplot(aes(get(val),freq)) +  
geom_bar(stat = "identity") 
}

我收到一个错误:" mutate_impl(.data,dots)中的错误:object' x'找不到"。

2 个答案:

答案 0 :(得分:1)

您并不真正需要count,因为您可以在没有geom_bar()调用的情况下使用stat来正确绘制它。只需将其转换为一个函数(由于您以编程方式使用它,请小心使用aes_)并使用lapply

plot_stuff <- function(x, val) {

  x %>%
    ggplot(aes_(x = as.name(val))) +
    geom_bar()

}

plots <- lapply(names(df), plot_stuff, x = df)

grid.arrange(grobs = plots, ncol = 3, nrow = 1)

enter image description here

答案 1 :(得分:0)

我们也可以使用for循环来获得解决方案。代码如下。但是,Jake提供的解决方案更好。

df = data.frame(x = sample(c("Large","Medium", "Small"), 10, replace = TRUE), y = sample(c("Yes","No"), 10, replace = TRUE), z = sample(c("High","Low"), 10, replace = TRUE) )

i <- c(0)
for (val in names(df)){
 i <- i+1
 assign(paste("bar",i,sep="_"), ggplot(df, aes_(as.name(val))) + geom_bar())
}
grid.arrange(bar_1, bar_2, bar_3, ncol = 3, nrow = 1)
```