0
votes

My toy data frame

A = c(4, 1, 0) 
B = c(0, 1, 0)
C = c(3, 0, 1)
D = c(2, 4, 1)
df = data.frame(A, B, C, D)

I am wanting to return a data frame that looks like this, Where for each row, column "E" has a value of "1" if any column A through D had a value of 3 or greater and a "0" otherwise:

  A B C D E
1 4 0 3 2 1
2 1 1 0 4 1
3 0 0 1 1 0

Attempt to create a new column called "E" with a value of "1" if any column from A to D had a value of 3 or greater, otherwise the value should be a "0".

library(tidyverse)
 df2  <- df %>% 
      mutate(E = ifelse(select(any_of(vars) >= 3, 1, 0)))

That didn't work... I also tried something with case_when

df2  <- df %>% 
      mutate(E = any_vars(case_when ((.) >= 3 ~ 1)) %>% 
      mutate(E = any_vars(case_when ((.) <3 ~ 0))

This also didn't work.

3

3 Answers

2
votes

I think this might be a possible solution:

mutate(df, E = ifelse(pmax(A,B,C,D)>=3,1,0))
1
votes

Try this with dplyr using c_across():

library(dplyr)
#Code
newdf <- df %>% rowwise() %>% mutate(E=as.numeric(length(which((c_across(A:D))>=3))>=1))

Output:

# A tibble: 3 x 5
# Rowwise: 
      A     B     C     D     E
  <dbl> <dbl> <dbl> <dbl> <dbl>
1     4     0     3     2     1
2     1     1     0     4     1
3     0     0     1     1     0

Or in base R using apply():

#Base R
df$E <- apply(df,1,function(x) as.numeric(length(which(x>=3))>=1))

Output:

  A B C D E
1 4 0 3 2 1
2 1 1 0 4 1
3 0 0 1 1 0
1
votes

Does this work:

> library(dplyr)
> df %>% rowwise() %>% mutate(E = case_when(any(A:D >=3) ~ 1, TRUE ~ 0))
# A tibble: 3 x 5
# Rowwise: 
      A     B     C     D     E
  <dbl> <dbl> <dbl> <dbl> <dbl>
1     4     0     3     2     1
2     1     1     0     4     1
3     0     0     1     1     0
>