Extracting unique numbers from string in R

前端 未结 7 2148
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:45

    For the second answer, you can use gsub to remove everything from the string that's not a number, then split the string as follows:

    unique(as.numeric(unlist(strsplit(gsub("[^0-9]", "", unlist(ll)), ""))))
    # [1] 7 6 1 5 2
    

    For the first answer, similarly using strsplit,

    unique(na.omit(as.numeric(unlist(strsplit(unlist(ll), "[^0-9]+")))))
    # [1]   7 667  11   5   2
    

    PS: don't name your variable list (as there's an inbuilt function list). I've named your data as ll.

提交回复
热议问题