how to extract the first number from each string in a vector in R?

后端 未结 7 1151
醉话见心
醉话见心 2020-12-18 10:53

I am new to regex in R. Here I have a vector where I am interested in extracting the first occurance of a number in each string of the vector .

I have a vector calle

7条回答
  •  借酒劲吻你
    2020-12-18 11:10

    One option is str_extract from stringr with an as.numeric wrap.

    > library(stringr)
    > as.numeric(str_extract(shootsummary, "[0-9]+"))
    # [1] 34 42 23 27 64
    

    Update In response to your question in the comments of this answer, here's a little explanation. The full explanation of a function can be found in its help file.

    • str_extract returns the first occurrence of the regular expression. It is vectorized over the character vector in its first argument.
    • The regular expression [0-9]+ matches any character of: '0' to '9' (1 or more times)
    • as.numeric changes the resulting character vector into a numeric vector.

提交回复
热议问题