R 从“完成日期”列添加月份和年份列

R 从“完成日期”列添加月份和年份列,r,date,R,Date,我有一列,日期格式为MM-DD-YYYY,日期格式为。 我想添加两列,一列只包含YYYY,另一列只包含MM 如何执行此操作?一个base R选项是使用sub删除子字符串,然后使用read.table df1[c('month', 'year')] <- read.table(text=sub("-\\d{2}-", ",", df1$date), sep=",") 注意:最好转换为datetime类,而不是使用字符串格式 df1 %>% mutate(date =mdy

我有一列,日期格式为MM-DD-YYYY,日期格式为。 我想添加两列,一列只包含YYYY,另一列只包含MM


如何执行此操作?

一个
base R
选项是使用
sub
删除子字符串,然后使用
read.table

df1[c('month', 'year')] <- read.table(text=sub("-\\d{2}-", ",", df1$date), sep=",") 
注意:最好转换为datetime类,而不是使用字符串格式

df1 %>%
     mutate(date =mdy(date), month = month(date), year = year(date))
数据
df1再一次,base R提供了您所需要的一切,您不应该使用子字符串来实现这一点

在这里,我们首先创建一个
data.frame
,其中包含一个适当的
Date
列。如果您的日期是文本格式,请首先使用
as.date()
或my
anytime::anydate()
(不需要格式)对其进行解析

然后给定日期,创建年份和月份很简单:

R> df <- data.frame(date=Sys.Date()+seq(1,by=30,len=10))
R> df[, "year"] <- format(df[,"date"], "%Y")
R> df[, "month"] <- format(df[,"date"], "%m")
R> df
         date year month
1  2017-12-29 2017    12
2  2018-01-28 2018    01
3  2018-02-27 2018    02
4  2018-03-29 2018    03
5  2018-04-28 2018    04
6  2018-05-28 2018    05
7  2018-06-27 2018    06
8  2018-07-27 2018    07
9  2018-08-26 2018    08
10 2018-09-25 2018    09
R> 
R>df-df[,“年”]df[,“月”]df
年月日
1  2017-12-29 2017    12
2  2018-01-28 2018    01
3  2018-02-27 2018    02
4  2018-03-29 2018    03
5  2018-04-28 2018    04
6  2018-05-28 2018    05
7  2018-06-27 2018    06
8  2018-07-27 2018    07
9  2018-08-26 2018    08
10 2018-09-25 2018    09
R>

如果您想将年或月作为整数,可以将格式包装为
as.integer()

您可以执行
库(tidyr);将(df1,日期,分为=c('month','day','year')%%>%选择(-day)
或使用
base R
read.table(text=sub(“-\\d{2}-”,“,”,df1$date),sep=“,”)
这是一个重复的问题,肯定是之前的许多问题,对吧?请不要建议使用字符串函数处理日期或时间。而且
tidyverse
肯定也太过了。
df1 <- data.frame(date = c("05-21-2017", "06-25-2015"))
R> df <- data.frame(date=Sys.Date()+seq(1,by=30,len=10))
R> df[, "year"] <- format(df[,"date"], "%Y")
R> df[, "month"] <- format(df[,"date"], "%m")
R> df
         date year month
1  2017-12-29 2017    12
2  2018-01-28 2018    01
3  2018-02-27 2018    02
4  2018-03-29 2018    03
5  2018-04-28 2018    04
6  2018-05-28 2018    05
7  2018-06-27 2018    06
8  2018-07-27 2018    07
9  2018-08-26 2018    08
10 2018-09-25 2018    09
R>