split character data into numbers and letters

后端 未结 7 1758
没有蜡笔的小新
没有蜡笔的小新 2020-12-02 15:45

I have a vector of character data. Most of the elements in the vector consist of one or more letters followed by one or more numbers. I wish to split each element in the

7条回答
  •  余生分开走
    2020-12-02 16:37

    You can also use colsplit from reshape2 to split your vector into character and digit columns in one step:

    library(reshape2)
    
    colsplit(my.data, "(?<=\\p{L})(?=[\\d+$])", c("char", "digit"))
    

    Result:

      char digit
    1  aaa    NA
    2    b    11
    3    b    21
    4    b   101
    5    b   111
    6  ccc     1
    7  ffffd     1
    8  ccc    20
    9  ffffd    13
    

    Data:

    my.data <- c("aaa", "b11", "b21", "b101", "b111", "ccc1", "ffffd1", "ccc20", "ffffd13")
    

提交回复
热议问题