测试dplyr中各列子集的平等性。

问题描述 投票:0回答:1

假设我有以下df。

mydf <- data.frame(col1 = c("Red", "Red", "Blue", "Orange"),
                   col2 = c("Red", "Blue", NA, "Red"),
                   col3 = c("Red", "Red", "Blue", "Red"),
                   col4 = c("Red", "Red", "Blue", "Blue"))

我想创建一个叫 "all_equal" 如果第1-4列的所有non_NA值都等于相同的值,则将其设为1。 结果应该是这样的。

    col1 col2 col3 col4 all_true
1    Red  Red  Red  Red     TRUE
2    Red Blue  Red  Red    FALSE
3   Blue <NA> Blue Blue     TRUE
4 Orange  Red  Red Blue    FALSE

请注意,第二列中的NA不应该算作平等。 我试过使用 all 来测试平等性,但似乎在dplyr链中效果不好。

r dplyr
1个回答
2
投票

您可以使用 c_across()rowwise().

library(dplyr)

mydf %>%
  rowwise() %>%
  mutate(all_true = n_distinct(c_across(col1:col4), na.rm = T) == 1) %>%
  ungroup()

# # A tibble: 4 x 5
#   col1   col2  col3  col4  all_true
#   <chr>  <chr> <chr> <chr> <lgl>   
# 1 Red    Red   Red   Red   TRUE    
# 2 Red    Blue  Red   Red   FALSE   
# 3 Blue   NA    Blue  Blue  TRUE    
# 4 Orange Red   Red   Blue  FALSE  

2
投票

dplyrpurrr 解决方案可能是。

mydf %>%
 mutate(all_equal = map_dbl(.x = transpose(select(., everything())), 
                            ~ n_distinct(na.omit(.x))) == 1)

  col1 col2 col3   col4 all_equal
1  Red Blue  Red    Red     FALSE
2  Red Blue  Red    Red     FALSE
3 Blue <NA>  Red Orange     FALSE

1
投票

在基础R中,你可以做

mydf$all_equal <- ifelse(apply(mydf, 1, function(x) length(unique(na.omit(x)))) == 1, TRUE, FALSE)

产量

#     col1 col2 col3 col4 all_equal
# 1    Red  Red  Red  Red      TRUE
# 2    Red Blue  Red  Red     FALSE
# 3   Blue <NA> Blue Blue      TRUE
# 4 Orange  Red  Red Blue     FALSE

0
投票

根据之前的答复 此处

mydf['all_true'] <- (rowSums(mydf == mydf[,1], na.rm=TRUE) + rowSums(is.na(mydf))) == ncol(mydf)
© www.soinside.com 2019 - 2024. All rights reserved.