简体   繁体   中英

regular expression match numbers in R

I want to compare Postal Codes encoded by 4 numbers which are factor labels in R. The problem is that in 1 format the fourth digit of these codes always is 0 and in another it can vary, so I have 1010 but also 1012, 1015, but they all mean the same. Therefore, I want to read the full postal codes and replace them by the 'standard code' with 0 as fourth digit.

v1 <- c(,"1011", "1015", "1017","1207","1209")
v2 <- c("1010","1200")

How can I read all factor levels as in the vector v1 above and systematically replace the last digit to look like vector v2 using regular expressions?

You will get the first three elements of a vector using:

    Three.str <- substr(v1, 1,3)

So, you can change all the factors starting with "101" using:

    v1[Three.str=="101"] <- "1010"

and so on with the corresponding codification you want to use.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM