String 如何将时间字段字符串作为字符变量从日期中删除?

String 如何将时间字段字符串作为字符变量从日期中删除?,string,r,substring,date-formatting,String,R,Substring,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") 您可以将它们转换为日期,然后根据需要设置格式,例如: v <- c("9/21/2011 0:00:00", "9/25/2011 0:00:00", "10/2/2011 0:00:00", "9/28/2011

假设我有一个这样的变量

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")

您可以将它们转换为日期,然后根据需要设置格式,例如:

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"

从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"
库(lubridate)

v使用
gsub
功能。在SO档案中一定有很多很多工作过的例子。你能用这个例子给我一个答案吗+1这可能很有用(strsplit(x,“\\s+””,“[”,1)
,但您可能希望实际使用此数据作为日期(
as.date
)。我认为问题并不是要求具有完全的通用性,而是如何将时间字段字符串作为字符变量从日期中删除?更简单的方法可以是使用
unit=“day”
on date types在
lubridate
@cengel中用于日期时间对象:好吧,OP的示例不是关于日期,而是包含日期的字符串,因此我宁愿避免加载外部包,只是为了从字符串中删除一些后缀。。。
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"
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)))