Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting values from strings with repeating structure

Tags:

string

r

Let's say I have a vector of strings, like this:

vectorOfStrings <- c("Name: Andrew, College: Bradford",
                     "Name: Charlie Daniels, College: Easton College",
                     "Name: Frank Gehry, III, College: Highlands University")

where there is a clear repeating "Name: ", ", College: " pattern.

I would like to produce a list (or data.frame) that looks like this:

listOfValues <- list(c("Andrew", "Charlie Daniels", "Frank Gehry, III"),
                     c("Bradford", "Easton College", "Highlands University"))

What is the most straightforward way to get from vectorOfStrings to listOfValues? I am reasonably familiar with the base string manipulation functions, as well as with stringr, but I would imagine this is a relatively common situation, and am hoping that there is a relatively well-developed solution.

Thanks in advance.

like image 933
isDotR Avatar asked Jul 22 '26 02:07

isDotR


1 Answers

Here are two possible solutions:

(1) strapplyc The mat statement creates a matrix whose first column holds the names and whose second holds the colleges. Then we convert that to an unnamed list in the last statement:

library(gsubfn)

pat <- "Name: (.*), College: (.*)"
mat <- strapplyc(vectorOfStrings, pat, simplify = rbind)

unname(as.list(as.data.frame(mat, stringsAsFactors = FALSE)))

(2) gsub/read.table A variation using only plain R is to use gsub with pat from above to convert each input string to a pipe-separated string containing the data but not the tags. Reading that in with read.table gives a data frame, DF. Finally, we convert DF to an unnamed list:

g <- gsub(pat, "\\1|\\2", vectorOfStrings)
DF <- read.table(text = g, sep = "|", as.is = TRUE)

unname(as.list(DF))

ADDED: second solution

like image 128
G. Grothendieck Avatar answered Jul 23 '26 18:07

G. Grothendieck