You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

R语言中按条件将数值型月份列转换为字符型月份缩写

数值型月份转英文缩写的正确实现方式

你的代码存在两个关键问题:

  • 管道操作符写错了,应该是%>%而非%>
  • R中不存在as.character<-这种赋值函数,你尝试给as.character()的结果赋值的语法完全错误

下面提供几种简洁的正确实现方法:

方法一:利用R内置月份缩写向量(推荐)

R内置了month.abb向量,包含12个月份的英文缩写(首字母大写),结合tolower()可以转成小写:

# base R 写法
all_trips$ride_months <- tolower(month.abb[all_trips$ride_months])

# dplyr 管道写法
library(dplyr)
all_trips <- all_trips %>%
  mutate(ride_months = tolower(month.abb[ride_months]))

原理:month.abb[1]对应"Jan",tolower()将其转为"jan",直接按数值索引匹配对应缩写,一步完成类型转换和值替换。

方法二:手动指定映射关系

如果需要自定义缩写(比如和内置不一致),可以用case_when逐个匹配:

library(dplyr)
all_trips <- all_trips %>%
  mutate(ride_months = case_when(
    ride_months == 1 ~ "jan",
    ride_months == 2 ~ "feb",
    ride_months == 3 ~ "mar",
    ride_months == 4 ~ "apr",
    ride_months == 5 ~ "may",
    ride_months == 6 ~ "jun",
    ride_months == 7 ~ "jul",
    ride_months == 8 ~ "aug",
    ride_months == 9 ~ "sep",
    ride_months == 10 ~ "oct",
    ride_months == 11 ~ "nov",
    ride_months == 12 ~ "dec"
  ))

内容的提问来源于stack exchange,提问作者user20517288

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 23:05:01