In R, how do I code "only show the first 2 words" of an output?

I have the following IF NA statement. I need to be able to only output the first two words.

if (is.na(name <- str_match(clean, "Middle Initial\n(.*?)\nADDRESS")))

name <- str_match(clean, "Middle Initial\n \n(.*?)\n5ADDRESS")

How would I assign only the first two words of the output to "name"?

Here's toy example if your data were structured as a tibble

library(dplyr)
library(magrittr)
library(tibble)
tib <- as.tibble(read.csv("toytib.csv", stringsAsFactors = FALSE))
tib
# A tibble: 3 x 5
  Name             Street            City        State Zip       
  <chr>            <chr>             <chr>       <chr> <chr>     
1 Harry Liversedge 2008 Elliot Road  Quantico    VA    22134-5030
2 Eric Eriksen     10 Dauphine St.   New Orleans LA    70146-5400
3 Alan Hale        4200 Wilson Blvd. Arlington   VA    22203-1804
new <- tib %>% select(Name, Street)
new
A tibble: 3 x 2
  Name             Street           
  <chr>            <chr>            
1 Harry Liversedge 2008 Elliot Road 
2 Eric Eriksen     10 Dauphine St.  
3 Alan Hale        4200 Wilson Blvd.

since without a reproducible example, called a reprex , I can only guess the data structure of clean.

2 Likes

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.