在输出中保留向量元素的名称

Keeping the the name of the vector element in the output

下面我的 foo 函数效果很好,但是它省略了与其向量输出相关联的名称。

对于下面的例子,我希望 foo 到 return:

    scale
[1] 2

但它只是 returns:

[1] 2

有解决办法吗?

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)

我们可以使用which.min获取索引,然后用它来对元素进行子集化。另外,循环一个命名向量

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

-测试

>  foo(h, study, scale)
scale 
    2 

您可以使用 summarise 并将 ... 传递给 across

来跳过 rlang 内容
library(dplyr)

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

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