我想按行检查多列是否全部相等。我想出了一种复杂的方法来计算每组每个值的出现次数。但这似乎有些……麻烦。
样本数据
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
}
Run Code Online (Sandbox Code Playgroud)
期望的输出
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
Run Code Online (Sandbox Code Playgroud)
由reprex 包(v0.2.1)于 2019-02-27 创建
不需要dplyr。我只是用它来展示我想要实现的目标。
有很多方法可以按行检查相等性。两个好办法:
# 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)
Run Code Online (Sandbox Code Playgroud)
如果您只想测试某些列,请使用列的子集而不是整个数据框:
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)
Run Code Online (Sandbox Code Playgroud)
请注意,当我想确保结果是 a即使长度为 1时,我会使用df[cols_to_test]而不是。df[, cols_to_test]data.framecols_to_test