22

我有一个看起来像这样的当前 DataFrame:

      DATETIME MEAS_AVG TARG_MIN TARG_AVG TARG_MAX DESPORT_NOTE
1  2012/04/10 14:03:37   0.2888     0.22     0.25     0.27      GOOD_PT
2  2012/03/30 07:48:17   0.2544     0.22     0.25     0.27      GOOD_PT
3  2012/03/24 19:23:08   0.2333     0.22     0.25     0.27      GOOD_PT
4  2012/03/25 16:10:17   0.2111     0.22     0.25     0.27      GOOD_PT
5  2012/04/10 00:58:29   0.2222     0.22     0.25     0.27      GOOD_PT
6  2012/04/14 18:32:52   0.2888     0.22     0.25     0.27      GOOD_PT
7  2012/04/21 14:47:47   0.2777     0.22     0.25     0.27      GOOD_PT

数据框被调用df3,我希望替换日期的特定列是df3$DATETIME

为了去除日期时间,我的代码中已经有了这个函数:

date <- strptime(df3$DATETIME, "%Y/%m/%d %H:%M:%S")

我希望用简单的月份名称替换所有日期时间信息。这是替换功能后的样子:

      DATETIME MEAS_AVG TARG_MIN TARG_AVG TARG_MAX DESPORT_NOTE
1  April   0.2888     0.22     0.25     0.27      GOOD_PT
2  March   0.2544     0.22     0.25     0.27      GOOD_PT
3  March   0.2333     0.22     0.25     0.27      GOOD_PT
4  March   0.2111     0.22     0.25     0.27      GOOD_PT
5  April   0.2222     0.22     0.25     0.27      GOOD_PT
6  April   0.2888     0.22     0.25     0.27      GOOD_PT
7  April   0.2777     0.22     0.25     0.27      GOOD_PT

我一直在寻找一个简单的替换列功能,但似乎找不到。我知道我可以使用as.Date()带有格式化的函数%B来返回未缩写的月份。唯一的问题是我不知道如何使用它来替换已经存在的列值。

我可以使用这个函数列出月份:

list(month=months(as.Date(df3$DATETIME)))
4

2 回答 2

31
df3$DATETIME <- months(as.Date(df3$DATETIME))
于 2012-11-05T20:26:39.833 回答
9

您可以覆盖不需要的列中的数据(如果需要,还可以重命名),而不是替换列。

为了转换数据,我将使用month()和ymd(),两者都来自lubridate包:

#install and load lubridate if not already done
install.packages("lubridate",repos="http://cran.us.r-project.org")
library(lubridate)

#transform data to month names
df3$DATETIME <-month(ymd(df3$DATETIME), label = TRUE, abbr = FALSE)

#rename if desired
names(df3)[which(names(df3)=="DATETIME")]<-"MONTH"

附录:我建议使用 lubridate 函数而不是months()来自 base R 的原因是它months()返回 char 类,而 lubridatemonth()返回一个有序因子,这可能很有用:

> #base function
> m2=months(as.Date("08/12/1990"))
> m1=months(as.Date("07/12/1990"))
> m1<m2
[1] FALSE
> 
> #lubridate
> m2=month(mdy("08/12/1990"),label=TRUE, abbr=FALSE)
 1 parsed with %m/%d/%Y
> m1=month(mdy("07/12/1990"),label=TRUE, abbr=FALSE)
 1 parsed with %m/%d/%Y
> m1<m2
[1] TRUE
> m1
[1] July
12 Levels: January < February < March < April < May < June < ... < December
> str(m1)
 Ord.factor w/ 12 levels "January"<"February"<..: 7
于 2012-11-05T20:35:46.070 回答