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

后端 未结 7 1161
醉话见心
醉话见心 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:06

    You can do this very nicely with the str_first_number() function from the strex package, or for more general needs, there's the str_nth_number() function.

    pacman::p_load(strex)
    shootsummary <- c("Aaron Alexis, 34, a military veteran and contractor ...",
                      "Pedro Vargas, 42, set fire to his apartment, killed six ...",
                      "John Zawahri, 23, armed with a homemade assault rifle ...",
                      "John Zawahri, 23, armed with a homemade assault rifle ...",
                      "Dennis Clark III, 27, shot and killed his girlfriend ...",
                      "Kurt Myers, 64, shot six people in neighboring ..."
    )
    str_first_number(shootsummary)
    #> [1] 34 42 23 23 27 64
    str_nth_number(shootsummary, n = 1)
    #> [1] 34 42 23 23 27 64
    

    Created on 2018-09-03 by the reprex package (v0.2.0).

提交回复
热议问题