Search code examples
rdataframedplyrdata-wrangling

Creating a large number of columns in R tidyverse based on a comparison with a specific column


I have a dataset in R tidyverse and I want to create 192 columns based on comparison with the sp column, just like the mp_comp_1 column. How can I do this for 192 columns in tidyverse?

library(tidyverse)    

df <- data.frame(matrix(ncol = 4, nrow = 3))

df%>%
  mutate(sp = c(34.9, 34.3, 34.4)) %>%
  mutate(mp_1 = c(35, 32.1, 34.4)) %>%
  mutate(mp_2 = c(30, 38.1, 39.4)) %>%
  mutate(mp_192 = c(34.9, 34.3, 30.4)) %>%
  select(sp, mp_1, mp_2, mp_192) %>%
  mutate(mp_comp_1= if_else(mp_1>sp, "bigger",
                            if_else(mp_1<sp, "smaller", "equal")))

enter image description here


Solution

  • You can make use of across and case_when.

    library(dplyr)
    
    df |> 
      mutate(across(starts_with("mp_"),
                    ~case_when(.x > sp ~ "bigger",
                               .x < sp ~ "smaller",
                               .x == sp ~ "equal"),
                    .names = "{.col}_comp"))
    
        sp mp_1 mp_2 mp_192 mp_1_comp mp_2_comp mp_192_comp
    1 34.9 35.0 30.0   34.9    bigger   smaller       equal
    2 34.3 32.1 38.1   34.3   smaller    bigger       equal
    3 34.4 34.4 39.4   30.4     equal    bigger     smaller
    

    Data

    df <- structure(list(sp = c(34.9, 34.3, 34.4), mp_1 = c(35, 32.1, 34.4
    ), mp_2 = c(30, 38.1, 39.4), mp_192 = c(34.9, 34.3, 30.4)), class = "data.frame", row.names = c(NA, 
    -3L))