访问传递给 map() 的列的名称

Access names of columns passed to map()

如何访问 purrr::map() 的输入名称?

此代码:

library(tidyverse)
library(janitor)

diamonds %>% 
    select(cut, color) %>%
    map( function(x)  janitor::tabyl(x)   ) 

输出这个:

$cut
          x     n    percent
1      Fair  1610 0.02984798
2      Good  4906 0.09095291
3 Very Good 12082 0.22398962
4   Premium 13791 0.25567297
5     Ideal 21551 0.39953652

$color
  x     n    percent
1 D  6775 0.12560252
2 E  9797 0.18162773
3 F  9542 0.17690026
4 G 11292 0.20934372
5 H  8304 0.15394883
6 I  5422 0.10051910
7 J  2808 0.05205784

但我正在尝试访问传递给映射的列的名称。 像这样(伪代码):

diamonds %>% 
    select(cut, color) %>%
    map( function(x) { table_1 <- janitor::tabyl(x)
                       table_1$column_name <- SOMEHOW_EXTRACT_NAME(x)
                      }
                     ) 

要使用列中输入的名称获得所需的输出:

$cut
          x     n    percent column_name
1      Fair  1610 0.02984798         cut
2      Good  4906 0.09095291         cut
3 Very Good 12082 0.22398962         cut
4   Premium 13791 0.25567297         cut
5     Ideal 21551 0.39953652         cut

$color
  x     n    percent column_name
1 D  6775 0.12560252       color
2 E  9797 0.18162773       color
3 F  9542 0.17690026       color
4 G 11292 0.20934372       color
5 H  8304 0.15394883       color
6 I  5422 0.10051910       color
7 J  2808 0.05205784       color

使用imap,您可以通过它访问名称作为第二个参数:

diamonds %>% 
    select(cut, color) %>%
    imap(
        function(x, name) { 
            table_1 <- janitor::tabyl(x)
            table_1$column_name <- name
            table_1
        }
    ) 

#$cut
#          x     n    percent column_name
#1      Fair  1610 0.02984798         cut
#2      Good  4906 0.09095291         cut
#3 Very Good 12082 0.22398962         cut
#4   Premium 13791 0.25567297         cut
#5     Ideal 21551 0.39953652         cut

#$color
#  x     n    percent column_name
#1 D  6775 0.12560252       color
#2 E  9797 0.18162773       color
#3 F  9542 0.17690026       color
#4 G 11292 0.20934372       color
#5 H  8304 0.15394883       color
#6 I  5422 0.10051910       color
#7 J  2808 0.05205784       color

diamonds %>% 
    select(cut, color) %>%
    imap( ~ { janitor::tabyl(.x) %>% mutate(column_name = .y) })

简称。