简体   繁体   中英

how to extract the specific words from a string in R?

how can I extract "7-9", "2-5" and "2-8", then paste to new column as event_time?
event_details
2.9(S) 7-9 street【Train】#2097
2.1(S) 2-5 street【Train】#2012
2.2(S) 2-8A TBC【Train】#202

You haven't really shared the logic to extract the numbers but based on limited data that you have shared we can do :

df$new_col <- sub('.*(\\d+-\\d+).*', '\\1', df$event_details)

df
#               event_details new_col
#1 2.9(S) 7-9 street【Train】     7-9
#2 2.1(S) 2-5 street【Train】     2-5
#3   2.2(S) 2-8A TBC【Train】     2-8

Or same using str_extract

df$new_col <- stringr::str_extract(df$event_details, "\\d+-\\d+")

data

df <- structure(list(event_details = structure(c(3L, 1L, 2L), 
.Label = c("2.1(S) 2-5 street【Train】", 
"2.2(S) 2-8A TBC【Train】", "2.9(S) 7-9 street【Train】"), class = 
"factor")), class = "data.frame", row.names = c(NA, -3L))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM