R语言新手求助:如何将整数日期列转换为年份列?
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

