R 检查变量的行值是否相等

R 检查变量的行值是否相等,r,dplyr,mutate,R,Dplyr,Mutate,我被卡住了。我有一个数据帧: test_df <- tibble(a = c(1,1,1), b = c(1,NA,2), c = c(1,1,1), d = c("a","b","c")) test_df # A tibble: 3 x 4 a b c d <dbl> <dbl> <dbl> <chr> 1 1 1 1 a 2 1 NA 1 b

我被卡住了。我有一个数据帧:

test_df <- tibble(a = c(1,1,1), b = c(1,NA,2), c = c(1,1,1), d = c("a","b","c"))

test_df

# A tibble: 3 x 4
      a     b     c d    
  <dbl> <dbl> <dbl> <chr>
1     1     1     1 a    
2     1    NA     1 b    
3     1     2     1 c
一种选择是:

test_df %>%
 rowwise() %>%
 mutate(equal = sd(c(a, b, c), na.rm = TRUE) == 0)

      a     b     c d     equal
  <dbl> <dbl> <dbl> <chr> <lgl>
1     1     1     1 a     TRUE 
2     1    NA     1 b     TRUE 
3     1     2     1 c     FALSE
test_df%>%
行()
突变(等于sd(c(a,b,c),na.rm=TRUE)==0)
a、b、c、d相等
真的吗
2 1 NA 1 b正确
3 1 2 1 c错误

另一个选项。检查数字之和除以数字的余数是否为0

test_df$equal <- apply(test_df[1:3], 1, function(x) sum(x, na.rm = T)%%sum(!is.na(x)) == 0)

test_df$equal我们可以从
matrixStats

library(matrixStats)
test_df$equal <- !rowSds(as.matrix(test_df[c('a', 'b', 'c')]), na.rm = TRUE)
test_df
# A tibble: 3 x 5
#      a     b     c d     equal
#  <dbl> <dbl> <dbl> <chr> <lgl>
#1     1     1     1 a     TRUE 
#2     1    NA     1 b     TRUE 
#3     1     2     1 c     FALSE
库(matrixStats)

test_df$equal Code只允许回答,但也鼓励解释答案。请考虑添加一些解释。+ 1,你有没有办法用<代码> pMAP?我原以为这可以工作
test_df%>%mutate(equal=pmap_dbl(list(a,b,c))~length(unique(na.omit(.))==1))
…但没有t@user63230,尝试使用mutate(equal=pmap_lgl(list(a,b,c))~length(unique(na.省略(c(…)))==1))
test_df %>%
    rowwise() %>%
    mutate(i = c(a, b, c) %>% unique %>% na.omit %>% length == 1)
test_df %>%
 rowwise() %>%
 mutate(equal = sd(c(a, b, c), na.rm = TRUE) == 0)

      a     b     c d     equal
  <dbl> <dbl> <dbl> <chr> <lgl>
1     1     1     1 a     TRUE 
2     1    NA     1 b     TRUE 
3     1     2     1 c     FALSE
test_df$equal <- apply(test_df[1:3], 1, function(x) sum(x, na.rm = T)%%sum(!is.na(x)) == 0)
library(matrixStats)
test_df$equal <- !rowSds(as.matrix(test_df[c('a', 'b', 'c')]), na.rm = TRUE)
test_df
# A tibble: 3 x 5
#      a     b     c d     equal
#  <dbl> <dbl> <dbl> <chr> <lgl>
#1     1     1     1 a     TRUE 
#2     1    NA     1 b     TRUE 
#3     1     2     1 c     FALSE