Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there an efficient way to rename variable with operator in name

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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(., '-', '_'))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading