将日期列转换为'期间年份'柱

时间:2015-04-12 09:47:55

标签: r string date syntax-error

我有4000个观察数据,所以这是head(both)

     kön             gdk   age fbkurs     pers   stterm
1    man          FALSE    69  FALSE 1941-12-23 2011-01-19
2    man             NA    70  FALSE 1942-02-11 2012-01-19
3 kvinna             NA    65  FALSE 1942-06-04 2007-09-01
4 kvinna           TRUE    68  FALSE 1943-04-04 2011-09-01
5 kvinna             NA    65  FALSE 1943-10-30 2008-09-01
6    man          FALSE    70   TRUE 1944-01-27 2013-09-01

我想根据名为' stterm'的列创建一个新列。 在stterm我有不同的日期,我宁愿命名为例如。 VT10,VT11等。我想调用新列regyear

我试图输入:

regyear <- factor(both$stterm, levels = c("2007-09-01"="HT07" "2008-09-01"="HT09" "2009-01-19"="VT09" "2009-09-01"="HT09" "2010-01-19"="VT10" "2010-09-01"="HT10" "2011-01-19"="VT11"
                                       "2011-09-01"="HT11" "2012-01-19"="VT12" "2012-09-01"="HT12" "2013-01-19"="VT13" "2013-09-01"="HT13" "2014-01-19"="VT14"))

但是当我这样做时,我收到以下错误消息:

Error: unexpected string constant in "regyear<- factor(both$stterm, levels = c("2007-09-01"='HT07' "2008-09-01""

我该怎么做才能使它们正确?

2 个答案:

答案 0 :(得分:4)

你的代码依赖于相当多的硬编码,这可能容易出错,如果你想要映射到句号的日期很多,那将会很乏味。

以下是一些替代方案,其中您的日期首先使用Date转换为课程as.Date。这样可以更容易地将月份提取并映射到“VT”或“HT”期间,并提取年份。

在第一个示例中,我使用cut“将x的范围划分为区间,并根据它们落入的区间对x中的值进行编码。”:

# some dates which are converted to proper R dates
dates <- as.Date(c("2006-09-01", "2007-02-01", "2008-09-01", "2009-01-19"))

# extract month
month <- as.integer(format(dates, "%m"))

# extract year
year <- format(dates, "%y")

# cut the months into intervals and label the levels
term <- cut(x = month, breaks = c(0, 8, 12), labels = c("VT", "HT"))

# paste 'term' and 'year' together
paste0(term, year)
# [1] "HT06" "VT07" "HT08" "VT09" 

在第二个示例中,findInterval用于创建区间索引的数字向量。该向量用于从“周期”向量中提取元素。然后将这些期间粘贴在上面的年份。

paste0(c("VT", "HT")[findInterval(x = month, vec = c(1, 9))], year)
# [1] "HT06" "VT07" "HT08" "VT09"

最后,一个类似的,更“手动”的方法,如果你有许多'休息'和你希望映射你的日期的间隔,那就不太方便了:

paste0(c("VT", "HT")[as.integer(month > 8) + 1], year)
# [1] "HT06" "VT07" "HT08" "VT09"

另一个相关的Q&amp; A here

答案 1 :(得分:2)

你可以这样做:

both$regyear<- factor(both$stterm, labels = c("2007-09-01"="HT07","2008-09-01"="HT09",
                                              "2011-01-19"="VT11","2011-09-01"="HT11",
                                              "2012-01-19"="VT12","2013-09-01"="HT13"))

原始代码中存在以下几个问题:

  1. 它没有在您的数据框中创建新变量:regyear<- factor(both$stterm, ...应为both$regyear<- factor(both$stterm, ...
  2. 级别/标签之间没有逗号。
  3. 您必须为给定的示例数据集提供多个级别(请参阅这些instructions on how to give a reproducable example)。
相关问题