R Extract day from date and time

Hi I only need to stay 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've tried this:

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

      

But I am getting the full date and is different from the original.

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

+5


source to share


6 answers


Are you looking for format

?



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

      

+18


source


If your dates are always in the same position and format, you have another option with substr()

. The call below starts from the 9th position - the beginning of the day - and ends on the 10th - the second day of the day.



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

      

+3


source


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

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

      

+2


source


Try:

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

      

+1


source


You can just use weekdays (df $ date) to extract the day of the week from the date. Just make sure the column is of type Date or convert using as.Date (). Hope this helps :)

0


source


If you have already set the variable class for the date type try

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

      

otherwise, nest the formatting function in the as.date function

0


source







All Articles