简体   繁体   English

如何使用read.csv导入4位数字的年份值而不是2位数字

[英]How to import 4-digit year value instead of 2-digit using read.csv

I need to import dates using read.csv. 我需要使用read.csv导入日期。 The date are in "dd-mm-yyyy" format in csv file. 该日期在csv文件中为“ dd-mm-yyyy”格式。 I've appended sample data below. 我在下面附加了示例数据。

UniqueId DOB UniqueId DOB

  1. 01-04-1984 1984年1月4日
  2. 24-08-1904 24-08-1904
  3. 12-12-2006 2006年12月12日
  4. 05-05-1870 1870年5月5日

Read.csv is converting the date into "dd-mm-yy" format even when I'm importing date as character. 即使我将日期导入为字符,Read.csv也会将日期转换为“ dd-mm-yy”格式。 I need it to import all 4-digit year. 我需要它来导入所有4位数字的年份。

My code and results are: 我的代码和结果是:

x <- read.csv("file", header=TRUE,colClasses =c("DOB"="character")) x <-read.csv(“ file”,header = TRUE,colClasses = c(“ DOB” =“字符”))

I also tried: 我也尝试过:

x <- read.csv("file", header=TRUE, stringsAsFactors = FALSE) x <-read.csv(“ file”,header = TRUE,stringsAsFactors = FALSE)

Result from both: 两者的结果:

UniqueId DOB UniqueId DOB

  1. 01-04-84 84年1月4日
  2. 24-08-04 24-08-04
  3. 12-12-06 06年12月12日
  4. 05-08-70 70年5月8日
 > class(x$DOB) [1] "character" 

When I use as.Date function on this, I get error values: 当我对此使用as.Date函数时,出现错误值:

> as.Date(dob$DOB, format="%d-%m-%y")  
[1] "01-04-1984" "24-08-2004" "12-12-2006" "05-08-1970"

I read that as.Date function automatically turns years between 00 and 68 into 21st Century years and years between 69 and 99 into 20th Century years. 我读为as.Date函数自动将00到68之间的年份转换为21世纪,而69到99之间的年份则自动转换为20世纪。

Thus, I think I'm making a mistake in read.csv function itself. 因此,我认为我在read.csv函数本身中犯了一个错误。

I haven't figured out the way of achieving what you want in one line, but if you can afford splitting the task into two lines, then try this: 我还没有找到在一行中实现所需目标的方法,但是如果您有能力将任务分成两行,则可以尝试以下方法:

library(dplyr) # data frame operations
library(lubridate) # tidyverse-compliant package for operations on dates

x <- read.csv("file.csv", header=TRUE, stringsAsFactors=FALSE)
x <- x %>% mutate(DOB = as.Date(DOB, format="%d-%m-%Y"))
x %>% mutate(year = lubridate::year(DOB)) # just to verify that the operations on dates work as expected
#   UniqueID        DOB year
# 1        1 1984-04-01 1984
# 2        2 1904-08-24 1904
# 3        3 2006-12-12 2006
# 4        4 1870-05-05 1870

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

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