0

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!

0

2 Answers 2

2

For the solution below it is necessary to install two packages: dplyr and lubridate.

# 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

I hope you find it useful. Happy coding in R!

Sign up to request clarification or add additional context in comments.

Comments

1

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")

1 Comment

Wow it actually works! Thanks a ton for your help. The date for act_weather_data wasn't properly formatted and all I had to do was to rearrange the format a little.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.