15

So regular expressions are something that I've always struggled a bit with / never spent the due time learning. In this case, I have an R vector of strings with baseball data in this format:

hit_vector = c("", "Batted ball speed <b>104 mph</b>; distance of <b>381 
feet</b>; launch angle of <b>38 degrees</b>.", 
"Ball was hit at <b>67 mph</b>.", "", "Ball left the bat at <b>107 mph</b> and traveled a distance of <b>412 feet</b>.", 
"Batted ball speed <b>71 mph</b>.", "Ball left the bat at <b>94 mph</b> and traveled a distance of <b>287 feet</b>.", 
"", "", "Batted ball speed <b>64 mph</b>.")  

> hit_vector
 [1] ""                                                                                                       
 [2] "Batted ball speed <b>104 mph</b>; distance of <b>381 feet</b>; launch angle of <b>38 degrees</b>."
 [3] "Ball was hit at <b>67 mph</b>."                                                                         
 [4] ""                                                                                                       
 [5] "Ball left the bat at <b>107 mph</b> and traveled a distance of <b>412 feet</b>."                        
 [6] "Batted ball speed <b>71 mph</b>."                                                                       
 [7] "Ball left the bat at <b>94 mph</b> and traveled a distance of <b>287 feet</b>."                         
 [8] ""                                                                                                       
 [9] ""                                                                                                       
[10] "Batted ball speed <b>64 mph</b>."  

I am trying to create a dataframe with 10 rows that looks like this:

hit_dataframe
    speed   distance   degrees
1.     NA         NA        NA
2.    104        381        38
3.     67         NA        NA
4.     NA         NA        NA
5.    107        412        NA
6.     71         NA        NA
7.     94        287        NA
8.     NA         NA        NA
9.     NA         NA        NA
10.    64         NA        NA

The entire hit_vector is much much longer, but it seems that they all follow this naming convention.

Edit: It looks like the following helps to identify some of the info, but these lines aren't working perfectly (the third line returns all FALSE, which isn't right):

grepl("[0-9]{1,3} mph", hit_vector)
grepl("[0-9]{1,3} feet", hit_vector)
grepl("[0-9]{1,3} degrees", hit_vector)

Edit2: I'm not sure how many digits each stat will be. For example mph could be over 100 (3 digits) and also less than 10 (1 digit).

2
  • 7
    I cannot sing the praises of regex101.com highly enough.
    – divibisan
    Commented Mar 26, 2018 at 21:30
  • thanks for the resource, really appreciate it!
    – Canovice
    Commented Mar 26, 2018 at 21:38

4 Answers 4

18

The str_extract function from the stringr package should be useful here:

data.frame(
    speed=str_extract(hit_vector, "(\\d+)(?=\\s+mph)"),
    distance=str_extract(hit_vector, "(\\d+)(?=\\s+feet)"),
    degrees=str_extract(hit_vector, "(\\d+)(?=\\s+degrees)")
)

#    speed distance degrees
# 1   <NA>     <NA>    <NA>
# 2    104      381      38
# 3     67     <NA>    <NA>
# 4   <NA>     <NA>    <NA>
# 5    107      412    <NA>
# 6     71     <NA>    <NA>
# 7     94      287    <NA>
# 8   <NA>     <NA>    <NA>
# 9   <NA>     <NA>    <NA>
# 10    64     <NA>    <NA>

\\d is a character class for digits, so \\d+ matches one or more digits. (?=) is a zero-width look-ahead operator, so in this case it matches patterns followed by zero or more whitespace characters (\\s+) and mph, feet, or degrees, without capturing these strings.

4
  • 2
    You need to be careful, the second row has 104,381 and 38
    – Onyambu
    Commented Mar 26, 2018 at 21:40
  • @Onyambu thanks, that's a good catch, I've updated the answer
    – cmaher
    Commented Mar 26, 2018 at 21:54
  • @Jan thanks, second time you've gotten me on that :)
    – cmaher
    Commented Mar 27, 2018 at 4:16
  • 1
    accepted this answer for conciseness, but this and answer below this using only base r are both great. thanks all
    – Canovice
    Commented Mar 29, 2018 at 19:28
14

using base r:

read.table(text=gsub("\\D+"," ",hit_vector),fill=T,blank.lines.skip = F)

    V1  V2 V3
1   NA  NA NA
2  104 381 38
3   67  NA NA
4   NA  NA NA
5  107 412 NA
6   71  NA NA
7   94 287 NA
8   NA  NA NA
9   NA  NA NA
10  64  NA NA

Here, just delete everything that is not numeric, ie \\D+ then read in the data, with FILL=T and without skipping

To take into consideration the comment you made below, then we would need to rearrange our data:

hit_vector1=c(hit_vector,"traveled a distance of <b>412 feet</b>.")

#Take the numbers together with their respective measurements.
a=gsub(".*?(\\d+).*?(mph|feet|degree).*?"," \\1 \\2",hit_vector1)

#Remove the </b>
b=sub("<[/]b>.","",a)

## Any element that does not contain the measurements, invoke an NA
fun=function(x){y=-grep(x,b);b<<-replace(b,y,paste(b[y],NA,x))}
invisible(sapply(c("mph","feet","degrees"),fun))

## Break the line after each measurement and read in a table format
e=gsub("([a-z])\\s","\\1\n",b)
unstack(read.table(text=e))
      degrees feet mph
1       NA   NA  NA
2       38  381 104
3       NA   NA  67
4       NA   NA  NA
5       NA  412 107
6       NA   NA  71
7       NA  287  94
8       NA   NA  NA
9       NA   NA  NA
10      NA   NA  64
11      NA  412  NA
1
  • This is good, but if there were a row in hit_vector with only distance (feet) data, like "traveled a distance of <b>412 feet</b>", this approach would put 412 in the 1st column (mph), not the 2nd
    – Canovice
    Commented Mar 27, 2018 at 1:58
2

If you don't mind red ink:

library(tidyverse)
tibble(x=hit_vector) %>%
  separate(x,c("speed","distance","degrees"),"</b>") %>%
  mutate_all(parse_number)

# # A tibble: 10 x 3
#    speed distance degrees
#    <dbl>    <dbl>   <dbl>
#  1    NA       NA      NA
#  2   104      381      38
#  3    67       NA      NA
#  4    NA       NA      NA
#  5   107      412      NA
#  6    71       NA      NA
#  7    94      287      NA
#  8    NA       NA      NA
#  9    NA       NA      NA
# 10    64       NA      NA
1
  • 1
    parse_number pushes through the warnings, deletes all non-numeric text, and returns an accurate number. Awesome tip!
    – Nettle
    Commented Aug 16, 2018 at 2:50
0

Yet another one in base R (using regmatches):

# list of patterns
patterns <- c("(\\d+)(?=\\s*mph)", "(\\d+)(?=\\s*feet)", "(\\d+)(?=\\s*degrees)")

results <- lapply(patterns, function(pattern) {
  unlist(lapply(hit_vector, function(item) {
    result <- as.numeric(regmatches(item, regexpr(pattern, item, perl = TRUE)))
    if (identical(result, numeric(0))) return(NA)
    else return(result)
  }))
})

# build the dataframe from the list
df <- as.data.frame(do.call(cbind, results))
colnames(df) <- c("speed", "distance", "degrees")


Or (the other way round):

result <- lapply(hit_vector, function(string) {
  unlist(lapply(patterns, function(pattern) {
    result <- as.numeric(regmatches(string, regexpr(pattern, string, perl = TRUE)))
    if (identical(result, numeric(0))) return(NA)
    else return(result)
  }))
})

df <- as.data.frame(do.call(rbind, result2))
colnames(df) <- c("speed", "distance", "degrees", "raw")


Both will yield

   speed distance degrees
1     NA       NA      NA
2    104      381      38
3     67       NA      NA
4     NA       NA      NA
5    107      412      NA
6     71       NA      NA
7     94      287      NA
8     NA       NA      NA
9     NA       NA      NA
10    64       NA      NA

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.