Extracting unique numbers from string in R

前端 未结 7 2142
Happy的楠姐
Happy的楠姐 2020-11-27 05:11

I have a list of strings which contain random characters such as:

list=list()
list[1] = \"djud7+dg[a]hs667\"
list[2] = \"7fd*hac11(5)\"
list[3] = \"2tu,g7gka         


        
7条回答
  •  心在旅途
    2020-11-27 05:50

    Here is yet another answer, this one using gregexpr to find the numbers, and regmatches to extract them:

    l <- c("djud7+dg[a]hs667", "7fd*hac11(5)", "2tu,g7gka5")
    
    temp1 <- gregexpr("[0-9]", l)   # Individual digits
    temp2 <- gregexpr("[0-9]+", l)  # Numbers with any number of digits
    
    as.numeric(unique(unlist(regmatches(l, temp1))))
    # [1] 7 6 1 5 2
    as.numeric(unique(unlist(regmatches(l, temp2))))
    # [1]   7 667  11   5   2
    

提交回复
热议问题