as.date funtion

Hi, I'm new in R, I'm trying to convert this string "Wed, Jan 6, 2016" to 2016-01-06 I used this sentence
x <- "Wed, Jan 6, 2016'
as.Date(x, format = "%Y-%m-%d")

but doesn't works, I appreciate your help

Congratulations on your first post.

You're mistaken.

The format is what tells the function how to read the input characters.
Let's tell it the pattern of the delimiter.

The days of the week are in the way, so it is best to remove them.

x <- "1-6-2016"
as.Date(x, format = "%m-%d-%Y")
x <- "1_6_2016"
as.Date(x, format = "%m_%d_%Y")
x <- "6_2016-1"
as.Date(x, format = "%d_%Y-%m")
x <- "1/6/2016"
as.Date(x, format = "%m/%d/%Y")

I will teach you the dictionary rdocumentation.

https://www.rdocumentation.org/packages/base/versions/3.6.2/topics/as.Date

Before asking questions, you should look for instructions and try running the sample code.

lubridate is a great package that further extends the recognition of the year and month.

library(lubridate)
x <- "1-6-2016"
mdy(x)
x <- "2016,Jan 6"
ymd(x)

Please continue to enjoy R.
If you have trouble with a function, use ? before the function.

?as.Date

Thank you for your help

Hi @cesarcruz01,
You can convert your date string with the day-of-the-week present as follows:

# help("strptime")  # Gives details about elements of the 'format=' string

x <- "Wed, Jan 6, 2016"
as.Date(x, format = "%A, %B %d, %Y")
#> [1] "2016-01-06"

# Confirm that the given date is a Wednesday
library(lubridate)
#> 
#> Attaching package: 'lubridate'
#> The following objects are masked from 'package:base':
#> 
#>     date, intersect, setdiff, union
wday(as.Date(x, format = "%A, %B %d, %Y"), label=TRUE, abbr=FALSE)
#> [1] Wednesday
#> 7 Levels: Sunday < Monday < Tuesday < Wednesday < Thursday < ... < Saturday

Created on 2021-06-15 by the reprex package (v2.0.0)

1 Like

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.