Home > Net >  dplyr mutate column while checking range of columns
dplyr mutate column while checking range of columns

Time:02-26

The code below shows how I am accomplishing this right now, but I am wondering if there is a way to do this with less code by using col1:col12, or something like that. I tried googling and couldn't figure it out.

MRE:

a = matrix(1:2,12,12)
a= as.data.frame(a)
a = a %>% mutate(col = case_when(V1 == 1 & V2 == 1 & V3 == 1 & V4 == 1 & V5 == 1 & V6 == 1 & V7 == 1 & V8 == 1 & V9 == 1 & V10 == 1 & V11 == 1 & V12 == 1~0)) %>% mutate(col = ifelse(is.na(col),1,col))

There is a lot of code and I know there must be a faster way to do this. I have 12 columns with varying values and I need to check the values in all 12 (using & and |) to create dummy variables indicating whether each row contains specific values. In my actual data set there is a larger range of values in all 12 columns. Any help would be appreciated.

CodePudding user response:

Here you can use mutate() with c_across() to query all the columns in your condition.

library(tidyverse)

a <- matrix(1:2,12,12) %>% 
  as.data.frame()

a %>% 
  rowwise() %>% 
  mutate(col = as.numeric(!all(c_across(V1:V12) == 1)))
#> # A tibble: 12 x 13
#> # Rowwise: 
#>       V1    V2    V3    V4    V5    V6    V7    V8    V9   V10   V11   V12   col
#>    <int> <int> <int> <int> <int> <int> <int> <int> <int> <int> <int> <int> <dbl>
#>  1     1     1     1     1     1     1     1     1     1     1     1     1     0
#>  2     2     2     2     2     2     2     2     2     2     2     2     2     1
#>  3     1     1     1     1     1     1     1     1     1     1     1     1     0
#>  4     2     2     2     2     2     2     2     2     2     2     2     2     1
#>  5     1     1     1     1     1     1     1     1     1     1     1     1     0
#>  6     2     2     2     2     2     2     2     2     2     2     2     2     1
#>  7     1     1     1     1     1     1     1     1     1     1     1     1     0
#>  8     2     2     2     2     2     2     2     2     2     2     2     2     1
#>  9     1     1     1     1     1     1     1     1     1     1     1     1     0
#> 10     2     2     2     2     2     2     2     2     2     2     2     2     1
#> 11     1     1     1     1     1     1     1     1     1     1     1     1     0
#> 12     2     2     2     2     2     2     2     2     2     2     2     2     1

Created on 2022-02-25 by the reprex package (v2.0.1)

  • Related