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

R语言新手求助:如何将整数日期列转换为年份列?

Extract Year from Integer Date Column (YYYYMM Format)

Hey there! Let's get this sorted out for you. I notice your Date column is integers like 189507—which are in YYYYMM format (year followed by month)—and you want to pull out just the 4-digit year as an integer. Your current code isn't working because the date parsing logic doesn't match your data's structure, so let's fix that with a couple of straightforward approaches using the tidyverse tools you're already using.

Why Your Original Code Didn't Work

When you ran as.Date(as.character(year), "%Y"), you told R to parse a 4-digit year (%Y), but your input strings are 6 characters long (e.g., "189507"). R can't make sense of this mismatch, so it either returns incorrect dates or NA values—hence you weren't getting the integer year you wanted.

Solution 1: Direct String Subsetting

Since your Date integers follow a strict YYYYMM pattern, you can convert them to strings, grab the first 4 characters, and convert back to an integer:

library(tidyverse)
library(lubridate)

# Load your data
df <- read_csv("noaa-central-park.csv")

# Extract year via string subsetting
df <- df %>%
  mutate(year = as.integer(substr(as.character(Date), 1, 4)))

Solution 2: Use Lubridate to Parse & Extract Year

Lubridate has a handy ym() function built specifically for YYYYMM formatted values. You can use it to convert the integer to a year-month date object, then extract the year with the year() function:

df <- df %>%
  mutate(year = year(ym(Date)))

This method is more robust if you ever need to work with the full date later, but both approaches will give you the integer year column you're after.

Verify & Group

Once you've added the year column, grouping will work as expected:

tempByYears <- df %>%
  group_by(year)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:31:32