如何从日期为字符的变量中删除时间字符串?

Dav*_*d Z 12 string substring r date-formatting

假设我有一个像这样的变量

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")
Run Code Online (Sandbox Code Playgroud)

什么是快速删除所有0:00:00s的方法

c
[1] "9/21/2011" "9/25/2011" "10/2/2011" "9/28/2011" "9/27/2011"
Run Code Online (Sandbox Code Playgroud)

dig*_*All 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"
Run Code Online (Sandbox Code Playgroud)

或者,您可以" 0:00:00"使用gsub 删除子字符串:

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"
Run Code Online (Sandbox Code Playgroud)

  • 一种更简单的方法可以是使用[round](https://stat.ethz.ch/R-manual/R-devel/library/base/html/round.POSIXt.html)和`unit ="day"`日期类型 (6认同)
  • 使用 [round_date](https://lubridate.tidyverse.org/reference/round_date.html) 作为 `lubridate` 中的日期时间对象 (2认同)

Kay*_*yer 10

从 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"
Run Code Online (Sandbox Code Playgroud)

如果要将向量保持为字符类型,而不是日期类型:

v <- as.character(as.Date(mdy_hms(v)))
Run Code Online (Sandbox Code Playgroud)