The calculation function does not capture names during lapping

I am trying to allow access to the names of the list of graphs that I feed. I looked at a few other posts that seem very similar, but still not sure how to pass the name vector of my list to it.

require(mlbench)
require(gridExtra)
require(dplyr)
require(ggplot2)

data(Soybean)

dfs <- lapply(Soybean, function(x) data.frame(table(x, exclude = NULL)))

display_charts <- function(x){
  ggplot(data.frame(x) %>% select(x = 1, y = 2), aes(x = x, y = y)) + 
    geom_col(col = 'red',
             fill = 'green',
             alpha = 0.3) +
    labs(title = names(x),
         x = names(x),
         y = 'Frequency')
}

all_charts <- lapply(dfs, display_charts)

n <- length(all_charts)
nCol <- floor(sqrt(n))
do.call("grid.arrange", c(all_charts, ncol=nCol))

I tried to set up the function lapplyby adjusting the function display_chartsto take an argument nameand replacing names(x)with name, and then creating a vector of names called nms <- names(dfs), and then execute seq_along(dfs), display_charts, x = dfs, nm = nms, but that will not work.

This graph creates a grid of 6x6 frequency diagrams for the data set, but I would like the name to be the name of the name. I feel that it is looking squarely at me in the face, and I do not see it.

+4
source share
1

lapply dfs , :

# Replaced `all_charts <- lapply(dfs, display_charts)` with:
all_charts <- lapply(seq_along(dfs), function(i) display_charts(dfs[i]))

ggplot display_charts() x[[1]], :

display_charts <- function(x) {
  library(ggplot2)
  ggplot(x[[1]] %>% select(x = 1, y = 2), aes(x = x, y = y)) + 
    geom_col(col = 'red',
             fill = 'green',
             alpha = 0.3) +
    labs(title = names(x),
         x = names(x),
         y = 'Frequency')
}

enter image description here

+5

Source: https://habr.com/ru/post/1692815/


All Articles