我有一个变量,它是月份和年份的串联,以数字格式.月份的格式为1-12,而不是01-12.
我的变量看起来像:
mmyyyy
12014
22014
102014
52015
112015
Run Code Online (Sandbox Code Playgroud)
我正在寻找匹配月份或年份的正则表达式:
一年,我做了类似的事情:
year <- ifelse(grepl("2014", mmyyyy), 2014, ifelse(grepl("2015", mmyyyy), 2015, 2016))
Run Code Online (Sandbox Code Playgroud)
但是这个月,我正在挣扎.我的第一个想法是用空白替换2014,2015等,然后将结果转换为数字.
month <- as.numeric(gsub("[[^2014]]", "", mmyyyy))
Run Code Online (Sandbox Code Playgroud)
但在这里,我找不到合适的正则表达式.
最后,我想要一个带有数字年(yyyy)的变量/向量和一个带有数字月份的变量/向量.
使用tidyr
which 的可能解决方案将在一次调用中同时创建两个month
和year
列.
library(tidyr)
extract(df, mmyyyy, c("month", "year"), "(\\d+)(\\d{4})", convert = TRUE)
# month year
# 1 1 2014
# 2 2 2014
# 3 10 2014
# 4 5 2015
# 5 11 2015
Run Code Online (Sandbox Code Playgroud)
数据
df <- data.frame(mmyyyy = c(12014,
22014,
102014,
52015,
112015))
Run Code Online (Sandbox Code Playgroud)
一种选择是
# for the months:
> as.numeric(gsub("(.*)[0-9]{4}$", "\\1", x))
#[1] 1 2 10 5 11
# for the years:
> as.numeric(gsub(".*([0-9]{4})$", "\\1", x))
#[1] 2014 2014 2014 2015 2015
Run Code Online (Sandbox Code Playgroud)
这适用于任何4位数年份.