Return multiple columns in dplyr mutate

Well, you don’t have to modify your function. Just do this

CO2 %>%
  as_tibble() %>%
  mutate(
    conc2 = conc^2,
    across(c(Treatment), one_hot)$Treatment # see here
  ) 

Output

# A tibble: 84 x 7
   Plant Type   Treatment   conc uptake   conc2 Isnonchilled
   <ord> <fct>  <fct>      <dbl>  <dbl>   <dbl>        <int>
 1 Qn1   Quebec nonchilled    95   16      9025            1
 2 Qn1   Quebec nonchilled   175   30.4   30625            1
 3 Qn1   Quebec nonchilled   250   34.8   62500            1
 4 Qn1   Quebec nonchilled   350   37.2  122500            1
 5 Qn1   Quebec nonchilled   500   35.3  250000            1
 6 Qn1   Quebec nonchilled   675   39.2  455625            1
 7 Qn1   Quebec nonchilled  1000   39.7 1000000            1
 8 Qn2   Quebec nonchilled    95   13.6    9025            1
 9 Qn2   Quebec nonchilled   175   27.3   30625            1
10 Qn2   Quebec nonchilled   250   37.1   62500            1
# ... with 74 more rows

For mutation across many columns,

CO2 %>%
  as_tibble() %>%
  mutate(
    conc2 = conc^2,
    bind_cols(as.list(across(starts_with("T"), one_hot)))
  )

Output

# A tibble: 84 x 8
   Plant Type   Treatment   conc uptake   conc2 IsQuebec Isnonchilled
   <ord> <fct>  <fct>      <dbl>  <dbl>   <dbl>    <int>        <int>
 1 Qn1   Quebec nonchilled    95   16      9025        1            1
 2 Qn1   Quebec nonchilled   175   30.4   30625        1            1
 3 Qn1   Quebec nonchilled   250   34.8   62500        1            1
 4 Qn1   Quebec nonchilled   350   37.2  122500        1            1
 5 Qn1   Quebec nonchilled   500   35.3  250000        1            1
 6 Qn1   Quebec nonchilled   675   39.2  455625        1            1
 7 Qn1   Quebec nonchilled  1000   39.7 1000000        1            1
 8 Qn2   Quebec nonchilled    95   13.6    9025        1            1
 9 Qn2   Quebec nonchilled   175   27.3   30625        1            1
10 Qn2   Quebec nonchilled   250   37.1   62500        1            1
# ... with 74 more rows

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top