Skip to content
Prev 366763 / 398502 Next

Extracting first number after * in a character vector

Hi Abhinaba,
I'm sure that someone will post a terrifyingly elegant regular
expression that does this, but:

 ardat<-
 c([1] "     1 X[0,SMITH]   *              0             0             1 ",
 ...
numpoststar<-function(x) {
 xsplit<-unlist(strsplit(x,""))
 starpos<-which(xsplit=="*")
 # watch out for a missing asterisk, they cause an infinite loop
 if(length(starpos)) {
  digits<-c("0","1","2","3","4","5","6","7","8","9")
  while(!any(digits %in% xsplit[starpos])) starpos<-starpos+1
  return(as.numeric(xsplit[starpos]))
 }
 return(NA)
}

for(i in 1:length(ardat)) print(numpoststar(ardat[i]))

The observant will wonder why I didn't use sapply. Because for some
reason it returned the original strings rather than the numbers. I
dunno.

Jim
On Mon, Jan 23, 2017 at 11:29 PM, Abhinaba Roy <abhinabaroy09 at gmail.com> wrote: