R Extract day from datetime

冷暖自知 提交于 2021-01-02 05:34:15

问题


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


回答1:


Are you looking for format?

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



回答2:


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"



回答3:


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

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



回答4:


Try:

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



回答5:


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




回答6:


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().



来源:https://stackoverflow.com/questions/26043627/r-extract-day-from-datetime

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!