[英]Parse string, extract two-digit year and complete into four digit format
I have strings like我有像这样的字符串
y1 <- "AB99"
y2 <- "04CD"
y3 <- "X90Z"
y4 <- "EF09"
y5 <- "12GH"
where I need to extract the two digit year and complete it into a four digit format.我需要提取两位数年份并将其完成为四位数格式。 The input range is from 1990 - 2020.
输入范围为 1990 - 2020 年。
The output should be: output 应该是:
"1999"
"2004"
"1990"
"2009"
"2012"
I tried:我试过了:
fun <- function(x) {
year <- readr::parse_number(x)
if(year < 50) year <- paste0("20", year) else year <- paste0("19", year)
return(year)
}
This works fine, except for the years 2000 - 2009 (testcase y2
and y4
).这工作正常,除了 2000 - 2009 年(测试用例
y2
和y4
)。
Which functions can help me to also work fine on those years?哪些功能可以帮助我在那些年也能正常工作?
Using some basic regex, you can remove everything that is not a number and apply an ifelse()
to prefix 19 or 20 as appropriate:使用一些基本的正则表达式,您可以删除不是数字的所有内容,并根据需要将
ifelse()
应用于前缀 19 或 20:
# Example data
y <- c(
y1 = "AB99",
y2 = "04CD",
y3 = "X90Z",
y4 = "EF09",
y5 = "12GH"
)
# Extract only the number
num <- gsub("\\D", "", y)
paste0(ifelse(num >= "90", "19", "20"), num)
# [1] "1999" "2004" "1990" "2009" "2012"
Alternatively, working with integers:或者,使用整数:
num <- as.integer(gsub("\\D", "", y)) # or as.integer(readr::parse_number(y))
num + ifelse(num >= 90L, 1900L, 2000L)
# [1] 1999 2004 1990 2009 2012
A number doesn't have a leading 0
, therefore you don't get your desired output.数字没有前导
0
,因此您无法获得所需的 output。 Using stringr and the str_pad
function should solve your issue.使用 stringr 和
str_pad
function 应该可以解决您的问题。
fun <- function(x) {
year <- readr::parse_number(x)
if (year < 50) {
year <- paste0("20", stringr::str_pad(year, 2, side="left", "0"))
} else {
year <- paste0("19", year)
}
return(year)
}
Another hint: use return
instead of print
.另一个提示:使用
return
而不是print
。
The parse_number will return 4, single digit number of y2 case. parse_number 将返回 4,y2 案例的个位数。 To get desired output you can add one more condition on number of characters as given below:
要获得所需的 output,您可以在字符数上再添加一个条件,如下所示:
fun_1 <- function(x) {
year <- readr::parse_number(x)
#cat("year is ",year,"\n") #added for check
if(year < 50 & nchar(year)<2){
year <- paste0("20","0", year)
} else {
year <- paste0("19", year)
}
# cat("Year post changes",year,"\n") # added for check,
print(year)
}
output: output:
fun_1(y2)
year is 4
Year post changes 2004
I have added the cat step just for checks.我添加了 cat 步骤只是为了检查。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.