假设我有一个像这样的变量
c<-c("9/21/2011 0:00:00", "9/25/2011 0:00:00", "10/2/2011 0:00:00",
"9/28/2011 0:00:00", "9/27/2011 0:00:00")
什么是快速删除所有0:00:00
以便
c
[1] "9/21/2011" "9/25/2011" "10/2/2011" "9/28/2011" "9/27/2011"
答案 0 :(得分:16)
您可以将它们转换为日期,然后根据需要进行格式化,例如:
v <- c("9/21/2011 0:00:00", "9/25/2011 0:00:00", "10/2/2011 0:00:00",
"9/28/2011 0:00:00", "9/27/2011 0:00:00")
v <- format(as.POSIXct(v,format='%m/%d/%Y %H:%M:%S'),format='%m/%d/%Y')
> v
[1] "09/21/2011" "09/25/2011" "10/02/2011" "09/28/2011" "09/27/2011"
或者,您只需使用gsub:
删除" 0:00:00"
子字符串即可
v <- gsub(x=v,pattern=" 0:00:00",replacement="",fixed=T)
> v
[1] "9/21/2011" "9/25/2011" "10/2/2011" "9/28/2011" "9/27/2011"
答案 1 :(得分:2)
从lubridate软件包中:使用mdy_hms()
读取字符,如月,日,年和小时,分钟,秒,然后用as.Date()
包裹以除去时间。
library(lubridate)
v <- c("9/21/2011 0:00:00", "9/25/2011 0:00:00", "10/2/2011 0:00:00",
"9/28/2011 0:00:00", "9/27/2011 0:00:00")
v <- as.Date(mdy_hms(v))
v
# [1] "2011-09-21" "2011-09-25" "2011-10-02" "2011-09-28" "2011-09-27"
如果要将矢量保留为字符类型,而不是日期类型:
v <- as.character(as.Date(mdy_hms(v)))