r-如何从Date列中提取Month和Year,并为每个列再添加两列



我目前正在处理一个数据帧,它是从一个.csv文件中导入的,该文件有一个"日期";列:第一个图像

然后我想从";日期";列分别为月份和年份的两个新列,代码如下:

act_weather_data["Month"] <- format(as.Date(act_weather_data$Date), "%m") ## For Month
act_weather_data["Year"] <- format(as.Date(act_weather_data$Date), "%Y") ## For Year

然而,上面的代码起了作用,年份列似乎显示不正确:第二图像

看起来年份列使用的是日期,而不是可以从"日期"中看到的实际年份;日期";柱我不确定为什么";年份";列显示如下。有人能帮我吗?非常感谢!

对于下面的解决方案,需要安装两个包:dplyrlubridate

# Install the necessary packages
install.packages("dplyr")
install.packages("lubridate")
# Load the packages
library(dplyr)
library(lubridate)
# create dates dataframe
dates_dt <- data.frame(the_dates=seq(as.Date('2022-01-01'),
as.Date('2022-01-10'),
by='days'))
# Look at the dataframe
dates_dt
# Double check they are actually dates
class(dates_dt$the_dates)
# Extract the month
lubridate::month(dates_dt$the_dates)
# Extract the year
lubridate::year(dates_dt$the_dates)
# Perhaps you want the month name instead? no problem
month.name[lubridate::month(dates_dt$the_dates)]
# Now add a column for each
dates_dt <- dates_dt %>% 
mutate(year=lubridate::year(dates_dt$the_dates),
month=lubridate::month(dates_dt$the_dates),
month_name=month.name[lubridate::month(dates_dt$the_dates)])
# Have a look at the result
dates_dt

我希望你觉得它有用。快乐的R编码!

看起来它抓住了日期而不是年份。因此,当你的日期通过as.date((函数时,它的格式似乎不正确

看看这个

as.Date(act_weather_data$Date)

看起来像是自己,并相应地格式化

as.Date(act_weather_data$Date, format="%Y/%m/%d")

然后应用。与以前一样的格式即

Year=format(as.Date(act_weather_data$Date, format="%Y/%m/%d"),"%Y")

最新更新