[英]Plot multiple dataframes with lapply in R
I am trying to plot several dataframes (one plot per dataframe) with a lapply function, but despite all the posts on this subject I could not find an answer as I keep getting an error: the output list of plots is empty.我正在尝试使用 lapply 函数绘制多个数据框(每个数据框一个图),但是尽管有关于此主题的所有帖子,但我始终找不到答案,因为我不断收到错误:图的输出列表为空。
My data is structured like this:我的数据结构如下:
df1 <- mtcars %>% group_by(cyl) %>% tally()
colnames(df1) <- c('var', 'n')
df2 <- mtcars %>% group_by(gear) %>% tally()
colnames(df2) <- c('var', 'n')
dfList <- list(df1, df2)
dfList
[[1]]
# A tibble: 3 x 2
var n
<dbl> <int>
1 4 11
2 6 7
3 8 14
[[2]]
# A tibble: 3 x 2
var n
<dbl> <int>
1 3 15
2 4 12
3 5 5
I tried :我试过 :
make_hist <- function(xvar){
ggplot(dfList, aes_(x = ~var, y = as.name(xvar))) +
geom_col() }
plots <- lapply(names(dfList), make_hist)
plots
list()
plots[1]
[[1]]
NULL
Try this to plot your list of data frames.试试这个来绘制你的数据框列表。 Your
make_hist
function was adjusted to handle a single data.frame.您的
make_hist
函数已调整为处理单个 data.frame。 Then lapply
can apply make_hist
to each element of the list.然后
lapply
可以将make_hist
应用于列表的每个元素。
make_hist <- function(df){
ggplot(df, aes(x = var, y = n)) +
geom_col() }
plots <- lapply(dfList, make_hist)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.