giegie
giegie

Reputation: 463

Create a new data frame using a few conditions based on values in columns (in R)

I have a big data frame (df). I would like to create a new data frame based on the following conditions:

  1. if Xa >0 and Db, Ez, Uy and Kd = 0 then display "f" otherwise "o"
  2. if Xa = 0 and Db, Ez, Uy and Kd > 0 then display "m" otherwise "o"
df
   a  b c d
Xa 0  1 1 0
Db 1  0 6 1
Ez 4  0 5 0
Uy 4  0 1 0
Kd 2  0 1 3

result

   a  b c d
1  m  f o o

Upvotes: 0

Views: 50

Answers (1)

latlio
latlio

Reputation: 1587

Here's my solution. It involves transposing your given dataframe so that I can take advantage of case_when() which, by default, evaluates conditions column-wise. Currently your conditions (e.g. Xa, Db, etc) are rows. Then I transpose back to get your desired output.

library(dplyr)

new_df <- df %>%
  t() %>%
  as_tibble() %>%
  mutate(across(everything(), ~case_when(
    Xa > 0 & Db == 0 & Ez == 0 & Uy == 0 & Kd ==0 ~ "f",
    Xa == 0 & Db > 0 & Ez > 0 & Uy > 0 & Kd > 0 ~ "m",
    TRUE ~ "o"))) %>%
  t() %>%
  as_tibble() %>%
  distinct()

colnames(new_df) <- c("a", "b", "c", "d")

# A tibble: 1 x 4
  a     b     c     d    
  <chr> <chr> <chr> <chr>
1 m     f     o     o 

Upvotes: 1

Related Questions