代码之家  ›  专栏  ›  技术社区  ›  ViSa

如何在r中获取map函数中的每个向量/列名?

  •  0
  • ViSa  · 技术社区  · 5 年前

    plotting function 去看 counts all factors 属于 each factor column

    东风

    install.packages("gapminder")
    library(gapminder)
    
    gapminder %>% head()
    
    ########### output ###############
    
    country continent   year    lifeExp pop gdpPercap
    <fct>   <fct>   <int>   <dbl>   <int>   <dbl>
    Afghanistan Asia    1952    28.801  8425333 779.4453
    Afghanistan Asia    1957    30.332  9240934 820.8530
    Afghanistan Asia    1962    31.997  10267083    853.1007
    Afghanistan Asia    1967    34.020  11537966    836.1971
    Afghanistan Asia    1972    36.088  13079460    739.9811
    Afghanistan Asia    1977    38.438  14880372    786.1134
    

    发行 :我无法在下面的代码中获取列名称作为图表标题:

    gapminder %>% 
      select_if(is.factor) %>% 
    
      map(function(feature) {
        count(data.frame(x = feature), x) %>% 
    
      ggplot(aes(x = x, y = n)) +
      geom_col() +
      theme_minimal() +
      theme(axis.text.x = element_text(angle = 90)) +
    
      # issue here in getting column name as chart title
      labs(title = colnames(feature))
    
      # labs(title = colnames(x))
      })
    

    这看起来是个小问题,但无法找出如何为每个图表获取相应的列名

    2 回复  |  直到 5 年前
        1
  •  1
  •   Ronak Shah    5 年前

    你可以用 imap 而不是 map 这将使您能够访问列名和值。

    library(tidyverse)
    
    list_plot <- gapminder %>% 
                  select(where(is.factor)) %>%
                  imap(function(feature_value, feature_name) {
                    count(data.frame(x = feature_value), x) %>% 
                    ggplot(aes(x = x, y = n)) +
                    geom_col() +
                    theme_minimal() +
                    theme(axis.text.x = element_text(angle = 90)) +
                    labs(title = feature_name)
                  })
    
        2
  •  2
  •   Duck    5 年前

    library(gapminder)
    library(tidyverse)
    #Code
    gapminder %>% 
      select_if(is.factor) %>%
      pivot_longer(everything()) %>%
      group_by(name,value) %>%
      summarise(N=n()) %>%
      ggplot(aes(x = value, y = N)) +
      geom_col(fill='purple',color='black') +
      theme_minimal() +
      theme(axis.text.x = element_text(angle = 90)) +
      facet_wrap(.~name,nrow = 1,scales = 'free')
    

    输出:

    enter image description here