I am currently working on a data frame, which is imported from a .csv file that has a "Date" column: First Image
Then I wanted to extract the month and year from the "Date" column into two new columns respectively for month and year with the following code I made:
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
The above code worked however, the Year column seems to be displayed incorrectly: Second Image
It appears that the Year column is using the date but not the actual year that can be seen from the "Date" column. I'm not sure as to why the "Year" column appears like this. Would anyone be able to help me with this? Thanks a lot!
CodePudding user response:
Looks like it is grabbing the day instead of the year. So would seem that your date isn't properly formatted when it goes through the as.Date() function
See what this
as.Date(act_weather_data$Date)
looks like on its own and format accordingly
i.e.
as.Date(act_weather_data$Date, format="%Y/%m/%d")
Then apply.the formatting as before i.e
Year=format(as.Date(act_weather_data$Date, format="%Y/%m/%d"),"%Y")