用于检查 >3 列中的值是否全部相等的谓词函数

pra*_*ner 7 r dplyr

您正在分析一个数据框,并且似乎三个或更多相同的列。但是,你怎么知道呢?这是我经常遇到的问题,在检查两列以上时我还没有找到快速的 tidyverse 解决方案。

如果要比较两列,可以使用: mutate(is_equal = col_1 == col_2)

但你不能这样做: mutate(is_equal = col_1 == col_2 == col_3)

代表:

structure(list(col_1 = c(109, 109, 109, 109, 109, 109, 109, 109, 
109, 109, 109, 109, 77, 77, 78, 77), col_2 = c(109, 109, 109, 
109, 109, 109, 109, 109, 109, 109, 109, 109, 77, 77, 77, 77), 
    col_3 = c(109, 109, 109, 109, 109, 109, 109, 109, 109, 109, 
    109, 109, 77, 77, 77, 77)), row.names = c(NA, -16L), class = c("tbl_df", 
"tbl", "data.frame"))
Run Code Online (Sandbox Code Playgroud)

akr*_*run 7

我们可以使用if_all

\n
library(dplyr)\ndf1 %>% \n   mutate(is_equal = if_all(col_2:col_3, `==`, col_1))\n
Run Code Online (Sandbox Code Playgroud)\n

-输出

\n
# A tibble: 16 \xc3\x97 4\n   col_1 col_2 col_3 is_equal\n   <dbl> <dbl> <dbl> <lgl>   \n 1   109   109   109 TRUE    \n 2   109   109   109 TRUE    \n 3   109   109   109 TRUE    \n 4   109   109   109 TRUE    \n 5   109   109   109 TRUE    \n 6   109   109   109 TRUE    \n 7   109   109   109 TRUE    \n 8   109   109   109 TRUE    \n 9   109   109   109 TRUE    \n10   109   109   109 TRUE    \n11   109   109   109 TRUE    \n12   109   109   109 TRUE    \n13    77    77    77 TRUE    \n14    77    77    77 TRUE    \n15    78    77    77 FALSE   \n
Run Code Online (Sandbox Code Playgroud)\n