【问题标题】:Keeping the the name of the vector element in the output在输出中保留向量元素的名称
【发布时间】:2021-11-24 11:14:46
【问题描述】:

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

对于下面的示例,我希望 foo 返回:

    scale
[1] 2

但它只是返回:

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

【问题讨论】:

    标签: r function dplyr tidyverse rlang


    【解决方案1】:

    我们可以使用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 
    

    【讨论】:

    • HERE我发现了一个感兴趣的问题。
    【解决方案2】:

    您可以通过使用summarise 并将... 传递给across 来跳过r​​lang 内容

    library(dplyr)
    
    foo <- function(data, ...){
      data %>% 
        summarise(across(c(...), n_distinct)) %>% 
        unlist() %>% 
        .[which.min(.)]
    }
    
    foo(h, study, scale)
    #> scale 
    #>     2
    

    【讨论】:

      猜你喜欢
      • 2021-12-05
      • 1970-01-01
      • 2015-06-13
      • 1970-01-01
      • 1970-01-01
      • 2013-02-03
      • 1970-01-01
      • 1970-01-01
      • 2018-03-25
      相关资源
      最近更新 更多