Reputation: 3781
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
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
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
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
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
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
Reputation: 24535
Try:
sapply(strsplit(as.character(df$x), '-'), function(x) x[3])
[1] "24" "24" "11" "11" "16" "14"
Upvotes: 1