如何重命名多个观察?

How to rename multiple observations?

我在 r 中有一个包含三列的标题。其中一列是“week_days”。此列中的所有观察结果缩写如下:(mo,tu,we,th,fr,sa,su)。虽然我想将它们更改为(星期一、星期二...等等)。

知道我该怎么做吗?

我们可以创建一个名为vector的key/value来匹配和替换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]

其他解决方案:

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

与 dplyr recode:

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