GabyLP
GabyLP

Reputation: 3781

R Extract day from datetime

Hi I need to remain only with the day of each date:

df<-data.frame(x=c("2014-07-24 00:00:00", 
"2014-07-24 00:00:00", "2014-07-11", "2014-07-11" ,"2014-07-16" ,"2014-07-14"))
as.Date(df$x,format="%Y-%m-%d" )

I tried this:

df$dia<-as.Date(df$x, format="%d")

But I get a full date and different from the orginal.

I don't want to install another package to do this. How can I solve it? Thanks

Upvotes: 13

Views: 64685

Answers (7)

vladiim
vladiim

Reputation: 1960

It's a function in lubridate

library(lubridate)
day(date)

Upvotes: 0

Nupur Gulalkari
Nupur Gulalkari

Reputation: 9

You can simply use weekdays(df$date) to extract the day of the week from the date. Only make sure the column is of type Date or convert using as.Date().

Upvotes: -1

Sven Hohenstein
Sven Hohenstein

Reputation: 81693

Are you looking for format?

format(as.Date(df$x,format="%Y-%m-%d"), format = "%d")
# [1] "24" "24" "11" "11" "16" "14"

Upvotes: 31

Abhik Mitra
Abhik Mitra

Reputation: 21

If you have already set the class of the variable to date type then try

df$dia <- format(df$x, "%d")

else, nest the format function within as.date function

Upvotes: 1

lawyeR
lawyeR

Reputation: 7654

If your dates are always in the same position and format, you have another option with substr(). The call below starts with the 9th position -- the start of the day -- and ends with the 10th -- the second number of the day.

substr(x = df$x, start = 9, stop = 10)
[1] "24" "24" "11" "11" "16" "14"

Upvotes: 5

Rich Scriven
Rich Scriven

Reputation: 99331

Since your result will no longer be a date anyway, you could use gsub

gsub("(.*)[-]", "", df$x)
# [1] "24" "24" "11" "11" "16" "14"

Upvotes: 2

rnso
rnso

Reputation: 24535

Try:

sapply(strsplit(as.character(df$x), '-'), function(x) x[3])
[1] "24" "24" "11" "11" "16" "14"

Upvotes: 1

Related Questions