Home > Blockchain >  Keeping the the name of the vector element in the output
Keeping the the name of the vector element in the output

Time:10-04

My foo function below works great, however it omits the name associated with its vector output.

For the example below, I expect foo to return:

    scale
[1] 2

But it simply returns:

[1] 2

Is there fix for this?

library(tidyverse)
library(rlang)

txt = "
study scale
1     1
1     1
2     2
3     2
3     2
3     2
4     1
"
h <- read.table(text = txt,h=T)

foo <- function(data, ...){

  dot_cols <- rlang::ensyms(...)
  str_cols <- purrr::map_chr(dot_cols, rlang::as_string)
  
min(sapply(str_cols, function(i) length(unique(data[[i]]))))
 
}

foo(h, study, scale)

CodePudding user response:

We may use which.min to get the index and then use it to subset the element. Also, loop over a named vector

foo <- function(data, ...){

  dot_cols <- rlang::ensyms(...)
  str_cols <- purrr::map_chr(dot_cols, rlang::as_string)
  
  v1 <- sapply(setNames(str_cols, str_cols), 
        function(i) length(unique(data[[i]])))
  v1[which.min(v1)]
 
}

-testing

>  foo(h, study, scale)
scale 
    2 

CodePudding user response:

You can skip the rlang stuff by using summarise and passing ... to across

library(dplyr)

foo <- function(data, ...){
  data %>% 
    summarise(across(c(...), n_distinct)) %>% 
    unlist() %>% 
    .[which.min(.)]
}

foo(h, study, scale)
#> scale 
#>     2
  • Related