Converting letters to numbers in entire dataframe

后端 未结 4 965
攒了一身酷
攒了一身酷 2020-12-21 01:40

I am having trouble applying the chartr() function on all columns of my data frame for converting letters to numbers.

I managed doing it on single colum

相关标签:
4条回答
  • 2020-12-21 01:59

    Using dplyr

    library(dplyr)
    DF %>% mutate_each(funs(chartr("ACGT", "1234", .)))
    

    You get:

      ID POS1 POS2 POS3
    1  1   13   34   33
    2  2   32   22   24
    3  3   44   42   14
    
    0 讨论(0)
  • 2020-12-21 02:05
    > cbind(DF, setNames( lapply( DF[-1], chartr, old='ACGT', new='1234'), 
                          paste0("POS", 1:(length(DF)-1),"X"))  )
      ID POS1 POS2 POS3 POS1X POS2X POS3X
    1  1   AG   GT   GG    13    34    33
    2  2   GC   CC   CT    32    22    24
    3  3   TT   TC   AT    44    42    14
    
    0 讨论(0)
  • 2020-12-21 02:13

    Why not use lapply?

    DF2 <- DF ## to not overwrite the original DF
    DF2[-1] <- lapply(DF2[-1], chartr, old = "ACGT", new = "1234")
    DF2
    #   ID POS1 POS2 POS3
    # 1  1   13   34   33
    # 2  2   32   22   24
    # 3  3   44   42   14
    

    Now you have two data frames with equivalent column names which I find easier to compare than appending new columns to the old data. Especially when there are many many columns.

    0 讨论(0)
  • 2020-12-21 02:18

    You could also use mgsub from qdap

    library(qdap)
    DF[paste0('POS', 1:3,'X')] <- mgsub(c('A', 'C', 'G', 'T'), 1:4, 
                   as.matrix(DF[-1]))
    DF
    #  ID POS1 POS2 POS3 POS1X POS2X POS3X
    #1  1   AG   GT   GG    13    34    33
    #2  2   GC   CC   CT    32    22    24
    #3  3   TT   TC   AT    44    42    14
    
    0 讨论(0)
提交回复
热议问题