Try any of them. The first two use the base only R. The latter assumes that we want to return a numerical vector.
1) sub
s <- sub(".*:", ":", test) ifelse(test == s, NA, s)
If there can be several: in the line replace the pattern "^[^:]*:" .
2) strsplit
sapply(strsplit(test, ":"), function(x) c(paste0(":", x), NA)[2])
Do not use this if there can be several: per line.
3) strapplyc
library(gsubfn) s <- strapplyc(test, "(:.*)|$", simplify = TRUE) ifelse(s == "", NA, s) ## [1] ": 458" ": 1" NA
We can omit the ifelse line if "" is ok, not NA .
4) strapply If the idea is really that there are some digits in the string and we want to return the numbers or NA, try the following:
library(gsubfn) strapply(test, "\\d+|$", as.numeric, simplify = TRUE)
source share