【问题标题】:The function of tilde (~) in dplyr conditional selectdplyr条件选择中波浪号(~)的作用
【发布时间】:2022-12-28 12:17:04
【问题描述】:

假设我有一个如下所示的原始数据集。作为整理过程,我尝试选择没有 NA 值的列 - 或者删除带有 NA- 的列,引用this

原始数据

 #>   data_name col_a  col_b
 #>   <chr>      <int> <int>
 #> 1 data_a     30    NA
 #> 2 data_b     20    75
 #> 3 sum        50    NA

删除 NA 列的代码

data_without_na <- raw_data %>% select_if(~ !any(is.na(.)))
data_without_na

输出

#>   data_name col_a
#>   <chr>      <int>
#> 1 data_a     30    
#> 2 data_b     20    
#> 3 sum        50  

输出如我所愿,但我很困惑为什么在条件的开头需要波形符 (~)。

到目前为止,这是我的理解:

  • R 中的波浪号:将等式的左侧与右侧分开
  • !: 否定
  • any(is.na(.)):如果有任何 na 值,则每列的 true 或 false 值

波浪号如何在没有左侧变量的情况下工作?

【问题讨论】:

    标签: r dplyr


    【解决方案1】:

    中使用~等同于function(...)。基本上,~ converts a formula-like expression to a function。见下文:

    library(dplyr)
    
    df %>% 
      select_if(function(x) !any(is.na(x)))
    #>   data_name col_a
    #> 1    data_a    30
    #> 2    data_b    20
    #> 3       sum    50
    
    df %>% 
      select_if(~ !any(is.na(.)))
    #>   data_name col_a
    #> 1    data_a    30
    #> 2    data_b    20
    #> 3       sum    50
    

    我可以尝试进一步解释,但 StackOverflow 上有多个线程可以更好地解释这一点,所以我只参考那些:

    1. Tilde Dot in R (~.)
    2. Meaning of tilde and dot notation in dplyr

      数据:

      df <- read.table(text = " data_name col_a  col_b
       data_a     30    NA
       data_b     20    75
       sum        50    NA", header = T)
      

    【讨论】:

      猜你喜欢
      • 2013-02-03
      • 2021-09-15
      • 1970-01-01
      • 2013-10-13
      • 2013-08-03
      • 2019-07-07
      • 2019-04-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多