2017-02-03 22 views
-1
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循环,如何在count()命令中使用变量名称?

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

我收到一个错误:“错误在mutate_impl(。数据,点):对象“× ' 未找到”。

+1

'%>%'是'包dplyr' '计数()'函数是'plyr' 我也以我的问题包括在此。 –

回答

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

0

我们也可以使用循环得到解决。代码如下。但是,杰克提供的解决方案更好。

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) 
```