逐行测试多个(不是全部)列是否相等

时间:2019-02-27 14:19:35

标签: r

我有片刻的头脑,只是无法提出比以下解决方案更简单的解决方案。我想做一个明智的行检查是否所有列都相等或不相等。我想出了一种复杂的方法来计算每组每个值的出现次数。但这似乎有点...麻烦。

样本数据

sample_df <- data.frame(id = letters[1:6], group = rep(c('r','l'),3), stringsAsFactors = FALSE)
set.seed(4)
for(i in 3:5) {
  sample_df[i] <-  sample(1:4, 6, replace = TRUE)
  sample_df
}

所需的输出

library(tidyverse)    
sample_df %>% 
  gather(var, value, V3:V5) %>% 
  mutate(n_var = n_distinct(var)) %>% # get the number of columns
  group_by(id, group, value) %>% 
  mutate(test = n_distinct(var) == n_var ) %>% # check how frequent values occur per "var" 
  spread(var, value) %>%
  select(-n_var)

#> # A tibble: 6 x 6
#> # Groups:   id, group [6]
#>   id    group test     V3    V4    V5
#>   <chr> <chr> <lgl> <int> <int> <int>
#> 1 a     r     FALSE     3     3     1
#> 2 b     l     FALSE     1     4     4
#> 3 c     r     FALSE     2     4     2
#> 4 d     l     FALSE     2     1     2
#> 5 e     r     TRUE      4     4     4
#> 6 f     l     FALSE     2     2     3

reprex package(v0.2.1)于2019-02-27创建

不需要是dplyr。我只是用它来展示我想要实现的目标。

1 个答案:

答案 0 :(得分:1)

有很多方法可以逐行检查相等性。两种好方法:

# test that all values equal the first column
rowSums(df == df[, 1]) == ncol(df)

# count the unique values, see if there is just 1
apply(df, 1, function(x) length(unique(x)) == 1)

如果您只想测试某些列,请使用列的子集而不是整个数据框:

cols_to_test = c(3, 4, 5)
rowSums(df[cols_to_test] == df[, cols_to_test[1]]) == length(cols_to_test)

# count the unique values, see if there is just 1
apply(df[cols_to_test], 1, function(x) length(unique(x)) == 1)

当我想确保结果为df[cols_to_test]时,即使df[, cols_to_test]的长度为1,我也不使用data.frame而不是cols_to_test

相关问题