繁体   English   中英

R 将字符串“Jan\\n1990”转换为日期格式

[英]R convert string "Jan\n1990" to date format

我有一个 csv 文件,第一列(名为“month”)的月份数据格式为“Jan\\n1990”、“Feb\\n1990”等等。 当我使用 read.csv 函数(使用 stringsAsFactors = FALSE)读取 R 中的文件时,它将“月份”列读取为“chr”。 我想将其转换为日期格式。 我试过

month_1 <- as.Date(f4$month)

但它给出了错误

Error in charToDate(x) : 
  character string is not in a standard unambiguous format

如何将第一列转换为日期格式的列?

r ,使用lubridate包中的函数parse_date_time ,您可以将字符串转换为日期格式:

date <- c("Jan\n1990","Feb\n1990") # Example of character strings to convert into dates

library(lubridate)
parse_date_time(date, order = "bY")

[1] "1990-01-01 UTC" "1990-02-01 UTC"

基于as.Date的解决方案:

date <- c("Jan\n1990","Feb\n1990") 

as.Date(paste0("1",date), format="%d%b\n%Y")
# [1] "1990-01-01" "1990-02-01"

另一种选择是来自zoo as.yearmon

library(zoo)
as.Date(as.yearmon(date))
#[1] "1990-01-01" "1990-02-01"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM