0

我有一个字符向量,它表示无格式日期中的覆盖年份,它像这样:

     Period of coverage
1    1/1/2011 to 31/12/2011
2    1/1/2010 to 31/12/2010
3    1/1/2012 to 31/12/2012
4    1/1/2010 to 31/12/2010
5    1/1/2011 to 31/12/2011
6    1/1/2012 to 31/12/2012
7    1/1/2010 to 31/12/2010
8    1/1/2010 to 31/12/2010
9    1/1/2009 to 31/12/2009

我想知道如何将这些列转换为每个观察所代表的年份。每行都有相同的开始日期和结束日期(1/1 和 31/12)。

4

3 回答 3

1

假设您的数据存储在变量中period,并且所有日期的格式都如您所述保持不变,

yr = substr(period, 19, 22)
于 2018-04-10T14:55:24.153 回答
1

假设DF在最后的注释中以可重复的方式显示,删除最后一个斜杠之前的所有内容并转换为数字:

transform(DF, year = as.numeric(sub(".*/", "", `Period of coverage`)), check.names = FALSE)

给予:

      Period of coverage year
1 1/1/2011 to 31/12/2011 2011
2 1/1/2010 to 31/12/2010 2010
3 1/1/2012 to 31/12/2012 2012
4 1/1/2010 to 31/12/2010 2010
5 1/1/2011 to 31/12/2011 2011
6 1/1/2012 to 31/12/2012 2012
7 1/1/2010 to 31/12/2010 2010
8 1/1/2010 to 31/12/2010 2010
9 1/1/2009 to 31/12/2009 2009

另一种可能性是将其转换为 Date 类,首先注意as.Date忽略最后的垃圾:

to_year <- function(x, fmt) as.numeric(format(as.Date(x, fmt), "%Y"))
transform(DF, year = to_year(`Period of coverage`, "%d/%m/%Y"), check.names = FALSE)

笔记

Lines <- "     Period of coverage
1/1/2011 to 31/12/2011
1/1/2010 to 31/12/2010
1/1/2012 to 31/12/2012
1/1/2010 to 31/12/2010
1/1/2011 to 31/12/2011
1/1/2012 to 31/12/2012
1/1/2010 to 31/12/2010
1/1/2010 to 31/12/2010
1/1/2009 to 31/12/2009"
DF <- read.csv(text = Lines, check.names = FALSE, as.is = TRUE)
于 2018-04-10T15:01:04.017 回答
1

如果您的字符串始终具有相同的格式,您可以简单地使用子字符串并将其转换为日期:

    as.Date(substr("1/1/2011 to 31/12/2011",5,8), format="%Y") 
as.Date(substr("1/1/2011 to 31/12/2011",19,23), format="%Y")

如果字符串比较多变,但总是被“to”分割,你可以用 stringsplit 取消列出字符串,然后将其格式化为年份:

a <- "1/1/2011 to 31/12/2011"
a2 <- strsplit(a, "to") ;
a3 <- unlist(a2) ;
a4 <- as.Date(a3, format="%d/%m/%Y")
year = format(a4, format="%Y")
于 2018-04-10T15:01:50.417 回答