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

如何在R数据框中将‘年+月’格式的剩余租期转换为年份并保存新列

将剩余租期转换为年份数值的R实现方法

下面提供两种常用的实现方案,针对格式为X years Y months的remaining_lease列,计算总年份并存入新列:

基础R方案

无需额外安装包,直接用正则表达式提取数值计算:

# 假设数据框名为df
df$remaining_lease_years <- with(df, 
  as.numeric(sub(" years.*", "", remaining_lease)) + 
  as.numeric(sub(".* months", "", remaining_lease)) / 12
)
  • 逻辑:sub(" years.*", "", remaining_lease)提取年份数字,sub(".* months", "", remaining_lease)提取月份数字,将月份转换为年的小数部分后与年份相加,得到总租期年份。

tidyverse方案

使用dplyr和stringr包实现管道化操作,代码可读性更强:

library(dplyr)
library(stringr)

df <- df %>%
  mutate(
    # 提取年份和月份数字
    years = as.numeric(str_extract(remaining_lease, "\\d+(?= years)")),
    months = as.numeric(str_extract(remaining_lease, "\\d+(?= months)")),
    # 计算总年份
    remaining_lease_years = years + months / 12,
    # 可选:删除临时生成的years和months列
    .keep = "unused"
  )
  • 逻辑:str_extract配合正向预查\\d+(?= years)精准匹配年份数字,同理提取月份数字,再计算总年份。

异常格式处理(可选)

如果存在格式不规范的行(比如仅含年份/月份),可先统一格式:

# 补全年份为0的情况(如"04 months")
df$remaining_lease <- str_replace(df$remaining_lease, "^(\\d+) months$", "0 years \\1 months")
# 补全月份为0的情况(如"56 years")
df$remaining_lease <- str_replace(df$remaining_lease, "^(\\d+) years$", "\\1 years 0 months")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 14:10:25