Search code examples
rdataframenumbersextract

Extract number from a column with text & number


I have a data frame column that looks like this:

Chr1 Chr14 Chr19 Chr2 Chr8 Chr7

I want to create a new column which looks as follows: 1 14 19 2 8 7

I tried this code, but it didn't work for me: New$CHR_1 <- substr(OLD$CHR, 4, 4) %>% as.integer


Solution

  • You may use readr::parse_number to extract the number from the column.

    OLD <- data.frame(CHR = c("Chr1", "Chr14", "Chr19", "Chr2", "Chr8", "Chr7"))
    OLD$num <- readr::parse_number(OLD$CHR)
    OLD
    
    #    CHR num
    #1  Chr1   1
    #2 Chr14  14
    #3 Chr19  19
    #4  Chr2   2
    #5  Chr8   8
    #6  Chr7   7