Accessing all unknown columns in mutate function of r

  df <- tibble::tribble(  ~sev_curve, ~curve_type,  ~trend_date, ~weight,
                          "MILO",  'HOSPITALS',   '7/1/2020',      0.4,
                          'ALSO',  'PHYSICIANSC', '7/1/2020',      0.6)


df %>% mutate(new_column=#calls function on all columns of df)

So the above is roughly what I need. The df data.frame can have a number of different columns that the next line of code may not know about. But it needs to call a function on all of those columns to create a new column.

How do I access all columns from the df in the mutate function?

Upvotes: 2

Views: 254

Answers (1)

akrun
akrun

Reputation: 887118

We can use mutate_at

library(dplyr)
df %>%
   mutate_at(vars(-one_of(c("sev_curve", "weight"))), list(new = ~ n_distinct(.)))
# A tibble: 2 x 6
#  sev_curve curve_type  trend_date weight curve_type_new trend_date_new
#  <chr>     <chr>       <chr>       <dbl>          <int>          <int>
#1 MILO      HOSPITALS   7/1/2020      0.4              2              1
#2 ALSO      PHYSICIANSC 7/1/2020      0.6              2              1

Or without one_of

df %>%
   mutate_at(vars(-c("sev_curve", "weight")), list(new = ~ n_distinct(.)))

Upvotes: 2

Related Questions