Reputation: 9
extracting date information 2010/05/01 in R to create new column
I modified the attribute in Date format right now my format is M%/Day%/Year%
b<-as.Date(Date)
expected result 2010/02/01 result 0002-02-20
Upvotes: 0
Views: 41
Reputation:
You might find the package lubridate
helpful for this type of thing.
library(lubridate)
my_date <- "2010/05/01"
Convert to a date from format year/month/date using function ymd()
> ymd(my_date)
[1] "2010-05-01"
Extract the day using the function day()
> day(ymd(my_date))
[1] 1
Extract the month using the function month()
> month(ymd(my_date))
[1] 5
Upvotes: 0
Reputation: 538
Try the following:
# Create a date string
dateString <- "2010/05/01"
# Convert the date string to a Date object
date <- as.Date(dateString, format="%Y/%m/%d")
# Extract the year and month
year <- format(date, "%Y")
month <- format(date, "%b")
More information about date formats in R here
Upvotes: 1
Reputation: 887851
We need to specify the format
assuming that the format is 'Year' followed by 'month' and 'day'
as.Date(Date, format = "%Y/%m/%d")
Without the format
, it assumes the format to be "%Y-%m-%d" by default
Upvotes: 2