split character data into numbers and letters

后端 未结 7 1752
没有蜡笔的小新
没有蜡笔的小新 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条回答
  •  猫巷女王i
    2020-12-02 16:40

    With stringr, if you like (and slightly different from the answer to the other question):

    # load library
    library(stringr)
    #
    # load data
    my.data <- c("aaa", "b11", "b21", "b101", "b111", "ccc1", "ffffd1", "ccc20", "ffffd13")
    #
    # extract numbers only
    my.data.num <- as.numeric(str_extract(my.data, "[0-9]+"))
    #
    # check output
    my.data.num
    [1]  NA  11  21 101 111   1   1  20  13
    #
    # extract characters only
    my.data.cha <- (str_extract(my.data, "[aA-zZ]+"))
    # 
    # check output
    my.data.cha
    [1] "aaa" "b"   "b"   "b"   "b"   "ccc" "ffffd" "ccc" "ffffd"
    

提交回复
热议问题