Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/78.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 测试多个变量,如果它们==1_R - Fatal编程技术网

R 测试多个变量,如果它们==1

R 测试多个变量,如果它们==1,r,R,有没有可能以某种方式缩短这个时间?我不想总是问它是否等于1,只写一次。对|和&…都很好 test = data.frame(a=c(1,0,1,0,1), b=c(0,1,0,0,0), c=c(0,0,0,0,NA)) atest <- test %>% mutate(variable = case_when(a == 1 | b == 1 | c == 1 ~ 1,

有没有可能以某种方式缩短这个时间?我不想总是问它是否等于1,只写一次。对|和&…都很好

test = data.frame(a=c(1,0,1,0,1), 
                  b=c(0,1,0,0,0), 
                  c=c(0,0,0,0,NA))

atest <- test %>% 
  mutate(variable =
           case_when(a == 1 | b == 1 | c == 1 ~ 1,
                     TRUE ~ NA_real_))

# someting like this: case_when( a | b | c == 1)

有了新的dplyr代码

library(tidyverse)

test %>%
  as_tibble() %>%
  rowwise() %>% 
  mutate(j = c_across() %>% any(. == 1))
  


test %>%
  as_tibble() %>%
  rowwise() %>% 
  mutate(j = c_across() %>% all(. == 1))

有了新的dplyr代码

library(tidyverse)

test %>%
  as_tibble() %>%
  rowwise() %>% 
  mutate(j = c_across() %>% any(. == 1))
  


test %>%
  as_tibble() %>%
  rowwise() %>% 
  mutate(j = c_across() %>% all(. == 1))

下面是一些基本的R选项

+ Reduce("|",test)

双方都给予

[1] 1 1 1 0 1

下面是一些基本的R选项

+ Reduce("|",test)

双方都给予

[1] 1 1 1 0 1
如果只处理0和1,则可以执行以下操作:

do.call(pmax, c(test, na.rm=TRUE))
# [1] 1 1 1 0 1
如果只处理0和1,则可以执行以下操作:

do.call(pmax, c(test, na.rm=TRUE))
# [1] 1 1 1 0 1

使用rowSumstest>0applyas.matrixtest==1,1,anyMaybe+rowSumstest==1,TRUE>0如果没有1,你真的想要NA吗?使用rowSumstest>0applyas.matrixtest==1,1,anyMaybe+rowSumstest==1,TRUE>0如果没有1,你真的想要NA吗?我收到很多关于转换变量的警告,但是c_Cross的+1还不知道这个。我收到了很多关于转换变量的警告,但是c_Cross的+1还不知道这个。使用pmax的好主意,+1!使用pmax+1的好主意!