Home > OS >  How to rename multiple observations?
How to rename multiple observations?

Time:11-26

I have a tibble with three columns in r. One of the columns are "week_days". All the observations in this column are abbreviated like this: (mo,tu,we,th,fr,sa,su). Though I want to change them to (monday, tuesday... and so on).

any idea on how I can do this?

CodePudding user response:

We can create a named vector of key/value to match and replace the values in the original data column in base R

nm1 <- setNames(c("monday", 'tuesday', 'wednesday', 'thursday', 
       'friday', 'saturday', 'sunday'),
      c('mo', 'tu', 'we', 'th', 'fr', 'sa', 'sun')   )
df1$week_days <- nm1[df1$week_days]

CodePudding user response:

Other solutions:

with plyr

df1$week_days <- plyr::mapvalues(
  df1$week_days,
  c('mo', 'tu', 'we', 'th', 'fr', 'sa', 'sun'),
  c("monday", 'tuesday', 'wednesday', 'thursday','friday', 'saturday', 'sunday')
)
      

with dplyr recode:

df1 %>%
  mutate(week_days = recode(week_days,
                            mo = "monday",
                            tu = 'tuesday'
                            we = 'wednesday',
                            th = 'thursday',
                            fr = 'friday',
                            sa = 'saturday', 
                            sun = 'sunday'))
  • Related