在 R 中使用 map() 函数循环时如何获取变量名称而不是 x?

how to get name of variables instead of x when looping using map() functions in R?

我正在从数据集中在 numeric variables 上应用 用户定义的函数,但我没有获取他们的 name's x 当使用 map 函数应用时。如何在 map 函数中将 x 替换为 variable 名称?

数据集:hd_trn

age   sex     cp   trestbps chol   fbs   restecg thalach exang
<int> <fctr> <fctr> <int>   <int> <fctr> <fctr>  <int>   <fctr>

63  1   1   145 233 1   2   150 0   
67  1   4   160 286 0   2   108 1   
67  1   4   120 229 0   2   129 1   
37  1   3   130 250 0   0   187 0   
41  0   2   130 204 0   2   172 0   
56  1   2   120 236 0   0   178 0

用户定义函数按列计算高频元素

top_freq_elements <- function(x){
  table(x) %>% as.data.frame() %>% top_n(5, Freq) %>% arrange(desc(Freq))
}

应用函数

hd_trn %>% select_if(is.numeric) %>% map(., .f = top_freq_elements)

######### output #########
x      Freq
<fctr> <int>

54  51          
58  43          
55  41          
56  38          
57  38

desired:在上面的输出中,我希望获取变量名而不是 x

尝试使用 imap 重构下面的代码,但也没有给出变量名:

hd_trn %>% 
  select_if(is.numeric) %>% 
  imap(function(feature_value, feature_name){
    table(feature_value) %>% 
      as.data.frame() %>% #head()
      rename(feature_name = feature_value) %>% 
      top_n(5, Freq) %>% 
      arrange(desc(Freq))
  })

#########  output  #########

feature_name Freq
<fctr>       <int>

54  51          
58  43          
55  41          
56  38          
57  38

这可以使用例如rename 中的卷曲 {{:= 像这样:

top_freq_elements <- function(x){
  table(x) %>% as.data.frame() %>% top_n(5, Freq) %>% arrange(desc(Freq))
}

library(dplyr)
library(purrr)

hd_trn %>% 
  select_if(is.numeric) %>% 
  imap(function(feature_value, feature_name){
    table(feature_value) %>% 
      as.data.frame() %>% #head()
      rename({{feature_name}} := feature_value) %>% 
      top_n(5, Freq) %>% 
      arrange(desc(Freq))
  })
#> $age
#>   age Freq
#> 1  67    2
#> 2  37    1
#> 3  41    1
#> 4  56    1
#> 5  63    1
#> 
#> $sex
#>   sex Freq
#> 1   1    5
#> 2   0    1
#> 
#> $cp
#>   cp Freq
#> 1  2    2
#> 2  4    2
#> 3  1    1
#> 4  3    1
#> 
#> $trestbps
#>   trestbps Freq
#> 1      120    2
#> 2      130    2
#> 3      145    1
#> 4      160    1

您可以重命名每个列表中的第一列:

library(dplyr)
library(purrr)

iris %>% 
  select(where(is.numeric)) %>% 
  imap(function(feature_value, feature_name){
    table(feature_value) %>% 
      as.data.frame() %>% 
      rename_with(~feature_name, 1) %>% 
      slice_max(n = 5, Freq) %>% 
      arrange(desc(Freq))
  })