简体   繁体   中英

How to rename multiple observations?

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?

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]

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'))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM