ViSa
ViSa

Reputation: 2237

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

I am applying a user defined function on numeric variables from a dataset but instead of getting their name's I am getting x when applied using map function. How do I replace x with variable name in map functions?

dataset: 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

user defined function to calculate high freq elements column wise

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

Applying function

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: In the above output I am looking to get variable name instead of x

Tried reconstructing code below using imap but that is also not giving variable name:

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

Upvotes: 0

Views: 278

Answers (2)

Ronak Shah
Ronak Shah

Reputation: 389055

You can rename the 1st column in each list :

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))
  })

Upvotes: 1

stefan
stefan

Reputation: 124433

This could be achieved using e.g. curly-curly {{ and := in rename like so:

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

Upvotes: 0

Related Questions