Search code examples
rsubstringquotations

Checking if a vector starts with a number


I have a pretty straight forward question. Sorry if this has already been asked somewhere, but I could not find the answer... I want to check if genenames start with a number, and if they do start with a number, I want to add 'aaa_' to the genename. Therefor I used the following code:

geneName <- "2310067B10Rik"
if (is.numeric(substring(geneName, 1, 1))) {
  geneName <<- paste("aaaa_", geneName, sep="")
}

What I want to get back is aaaa_2310067B10Rik. However, is.numeric returns a FALSE, because the substring gives "2" in quotations as a character. I've also tries to use noquote(), but that didnt work, and as.numeric() around the substring, but then it also applies the if code to genes that don't start with a number. Any suggestions? Thanks!


Solution

  • geneName <- c("2310067B10Rik", "foo") 
    
    ifelse(substring(geneName, 1,1) %in% c(0:9), paste0("aaaa_", geneName), geneName)
    
    [1] "aaaa_2310067B10Rik" "foo"  
    

    Or based on above comment, you could replace substring(geneName, 1,1) %in% c(0:9) by grepl("^\\d", geneName)