My data has a bunch of variables with names like 'day-30', 'day-2' and so on, is there an easier way to convert them to day_30, day_2 and so on at one swoop?
example = data.frame(ID = c(1,1,1,2,2),
time0 = c('2009-01-01','2009-01-01','2009-01-01','2005-02-02','2001-01-31'),
obs_num = c('A','D','B','B', 'Z'),
recorded_dt = c('2009-01-01 ','2009-01-31','2009-01-05','2005-02-03', '2001-01-01'))
example %>%
mutate(difs_days = floor(difftime(recorded_dt, time0, units="days"))) %>%
arrange(difs_days) %>%
pivot_wider(names_from = difs_days, values_from = obs_num, names_prefix = 'day') %>%
arrange(ID, recorded_dt)
I want to rename the one that has day-30.
Thanks.
CodePudding user response:
Use rename_with
with str_replace_all
:
library(stringr)
library(dplyr)
example %>%
mutate(difs_days = floor(difftime(recorded_dt, time0, units="days"))) %>%
arrange(difs_days) %>%
pivot_wider(names_from = difs_days, values_from = obs_num, names_prefix = 'day') %>%
arrange(ID, recorded_dt) %>%
rename_with(., ~str_replace_all(., '-', '_'))