3

I have an output of web scraped data in R which looks as follows

Name1
Email: email1@xyz.com
City/Town: Location1
Name2
Email: email2@abc.com
City/Town: Location2
Name3
Email: email3@pqr.com
City/Town: Location3

Some names may not have email or location. I want convert above data into tabular format. The output should look like

Name      Email           City/Town
Name1   email1@xyz.com  Location1
Name2   email2@abc.com  Location2
Name3   email3@pqr.com  Location3
Name4                   Location4
Name5   email5@abc.com  
Yash
  • 31
  • 1
  • Source data looks like this. Name1 Email: email1@abc.com City/Town: Location1 Name2 Email: email2@xyz.com City/Town: Location2 Name3 Email: email3@pqr.com City/Town: Location3 – Yash Jun 28 '17 at 06:47
  • Can you provide a [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example)? – Samuel Jun 28 '17 at 06:48

5 Answers5

4

Using:

txt <- readLines(txt)

library(data.table)
library(zoo)

dt <- data.table(txt = txt)

dt[!grepl(':', txt), name := txt
   ][, name := na.locf(name)
     ][grepl('^Email:', txt), email := sub('Email: ','',txt)
       ][grepl('^City/Town:', txt), city_town := sub('City/Town: ','',txt)
         ][txt != name, lapply(.SD, function(x) toString(na.omit(x))), by = name, .SDcols = c('email','city_town')]

gives:

    name          email city_town
1: Name1 email1@xyz.com Location1
2: Name2 email2@abc.com Location2
3: Name3 email3@pqr.com Location3
4: Name4                Location4
5: Name5 email5@abc.com          

This also works with real names. With the data of @uweBlock you'll get:

                  name          email city_town
1:            John Doe email1@xyz.com Location1
2: Save the World Fund email2@abc.com Location2
3:     Best Shoes Ltd. email3@pqr.com Location3
4:              Mother                Location4
5:                Jane email5@abc.com

And with multiple keys per section (again with @UweBlock's data):

                  name                          email             city_town
1:            John Doe email1@xyz.com, email1@abc.com             Location1
2: Save the World Fund                 email2@abc.com             Location2
3:     Best Shoes Ltd.                 email3@pqr.com             Location3
4:              Mother                                Location4, everywhere
5:                Jane                 email5@abc.com

Used data:

txt <- textConnection("Name1
Email: email1@xyz.com
City/Town: Location1
Name2
Email: email2@abc.com
City/Town: Location2
Name3
Email: email3@pqr.com
City/Town: Location3
Name4
City/Town: Location4
Name5
Email: email5@abc.com")
Jaap
  • 81,064
  • 34
  • 182
  • 193
4

Insert \nName: before each Name and then read it in using read.dcf (If the data comes from a file replace textConnection(Lines) with the filename, e.g. "myfile.dat", in the first line of code.) No packages are used.

L <- trimws(readLines(textConnection(Lines)))
ix <- !grepl(":", L)
L[ix] <- paste("\nName:", L[ix])
read.dcf(textConnection(L))

giving the following using the input in the Note at the end:

     Name    Email            City/Town  
[1,] "Name1" "email1@xyz.com" "Location1"
[2,] "Name2" NA               "Location2"
[3,] "Name3" "email3@pqr.com" NA         

Note: Input used. This is slightly modified from question to show that it works if Email or City/Town is missing:

Lines <- "Name1
Email: email1@xyz.com
City/Town: Location1
Name2
City/Town: Location2
Name3
Email: email3@pqr.com"
Jaap
  • 81,064
  • 34
  • 182
  • 193
G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341
  • All other answers are solving Y problem, this one is solving the X! – zx8754 Jul 05 '17 at 19:51
  • Nice answer! `read.dcf` isn't a very well know function I guess (though available in base R) – Jaap Jul 05 '17 at 19:57
  • A good demonstration of the benefits of learning base R well. If the parameter `all = TRUE` is used with `read.dcf()` the solution is also able to handle duplicate entries, e.g., multiple email addresse, like in the `txt2` sample data set [here](https://stackoverflow.com/a/44918481/3817004). – Uwe Jul 06 '17 at 06:54
3

The input data offer several challenges:

  • Data are given as a straight character vector, not a as data.frame with predefined columns.
  • The rows partly consist of key/value pairs which are separated by ": "
  • The other rows act as section headers. All key/value pairs in the rows below belong to one section until the next header is reached.

The code below is relying only on two assumptions:

  1. key/value pairs contain one and only one ": "
  2. section headers none at all.

Multiple keys in a section, e.g., multiple rows with email adresses are handled by specifying toString() as aggregation function to dcast().

library(data.table)
# coerce to data.table
data.table(text = txt)[
  # split key/value pairs in columns
  , tstrsplit(text, ": ")][
    # pick section headers and create new column 
    is.na(V2), Name := V1][
      # fill in Name into the rows below
      , Name := zoo::na.locf(Name)][
        # reshape key/value pairs from long to wide format using Name as row id
        !is.na(V2), dcast(.SD, Name ~ V1, fun = toString, value.var = "V2")]
    Name City/Town          Email
1: Name1 Location1 email1@xyz.com
2: Name2 Location2 email2@abc.com
3: Name3 Location3 email3@pqr.com
4: Name4 Location4             NA
5: Name5        NA email5@abc.com

Data

txt <- c("Name1", "Email: email1@xyz.com", "City/Town: Location1", "Name2", 
"Email: email2@abc.com", "City/Town: Location2", "Name3", "Email: email3@pqr.com", 
"City/Town: Location3", "Name4", "City/Town: Location4", "Name5", 
"Email: email5@abc.com")

Or, try somewhat more "realistic" names

txt1 <- c("John Doe", "Email: email1@xyz.com", "City/Town: Location1", "Save the World Fund", 
"Email: email2@abc.com", "City/Town: Location2", "Best Shoes Ltd.", "Email: email3@pqr.com", 
"City/Town: Location3", "Mother", "City/Town: Location4", "Jane", 
"Email: email5@abc.com")

which will result in:

                  Name City/Town          Email
1:     Best Shoes Ltd. Location3 email3@pqr.com
2:                Jane        NA email5@abc.com
3:            John Doe Location1 email1@xyz.com
4:              Mother Location4             NA
5: Save the World Fund Location2 email2@abc.com

Or, with multiple keys per section

txt2 <- c("John Doe", "Email: email1@xyz.com", "Email: email1@abc.com", "City/Town: Location1", "Save the World Fund", 
"Email: email2@abc.com", "City/Town: Location2", "Best Shoes Ltd.", "Email: email3@pqr.com", 
"City/Town: Location3", "Mother", "City/Town: Location4", "City/Town: everywhere", "Jane", 
"Email: email5@abc.com")
                  Name             City/Town                          Email
1:     Best Shoes Ltd.             Location3                 email3@pqr.com
2:                Jane                                       email5@abc.com
3:            John Doe             Location1 email1@xyz.com, email1@abc.com
4:              Mother Location4, everywhere                               
5: Save the World Fund             Location2                 email2@abc.com
Community
  • 1
  • 1
Uwe
  • 41,420
  • 11
  • 90
  • 134
3

Using dplyr and tidyr, tested on both data provided by @Jaap txt, and by @UweBlock txt1:

library(dplyr)
library(tidyr)

# data_frame(txt = txt1) %>%     
data_frame(txt = txt) %>% 
  mutate(txt = if_else(grepl(":", txt), txt, paste("Name:", txt)),
         rn = row_number()) %>% 
  separate(txt, into = c("mytype", "mytext"), sep = ":") %>% 
  spread(key = mytype, value = mytext) %>% 
  select(-rn) %>% 
  fill(Name) %>% 
  group_by(Name) %>% 
  fill(1:2, .direction = "down") %>% 
  fill(1:2, .direction = "up") %>% 
  unique() %>% 
  ungroup() %>% 
  select(3:1)

# # A tibble: 5 x 3
#     Name           Email `City/Town`
#    <chr>           <chr>       <chr>
# 1  Name1  email1@xyz.com   Location1
# 2  Name2  email2@abc.com   Location2
# 3  Name3  email3@pqr.com   Location3
# 4  Name4            <NA>   Location4
# 5  Name5  email5@abc.com        <NA>

Notes:

  • See here why we need rn.
  • Hoping someone will suggest better/simpler code using only tidyverse.
zx8754
  • 52,746
  • 12
  • 114
  • 209
  • 1
    Simpler: `data_frame(text = txt) %>% separate_rows(text, sep = '\n') %>% separate(text, c('var', 'val'), sep = ': ', fill = 'left') %>% mutate(entry = cumsum(is.na(var)), var = coalesce(var, 'Name')) %>% spread(var, val) %>% select(4:2)` where `txt` is a character vector or path. Or use `data_frame(text = read_lines(txt))` instead of `separate_rows`. – alistaire Jul 05 '17 at 17:52
  • @alistaire Couldn't make it work with txt2, duplicated rows error. Maybe add rn? Also, maybe add as a new answer or I can add to mine? – zx8754 Jul 05 '17 at 19:21
  • You can group and summarize with `toString`, e.g. `data_frame(text = txt2) %>% #separate_rows(text, sep = '\n') %>% separate(text, c('var', 'val'), sep = ': ', fill = 'left') %>% mutate(entry = cumsum(is.na(var)), var = coalesce(var, 'Name')) %>% group_by(entry, var) %>% summarise(val = toString(val)) %>% spread(var, val) %>% ungroup() %>% select(4:2)` or add an index to the keys, but I don't really love either option. Go ahead and add it if you like. – alistaire Jul 05 '17 at 20:13
2

Benchmarks:

Code:

txt2 <- c("John Doe", "Email: email1@xyz.com", "Email: email1@abc.com", "City/Town: Location1", "Save the World Fund", 
          "Email: email2@abc.com", "City/Town: Location2", "Best Shoes Ltd.", "Email: email3@pqr.com", 
          "City/Town: Location3", "Mother", "City/Town: Location4", "City/Town: everywhere", "Jane", 
          "Email: email5@abc.com")

library(microbenchmark)
library(data.table)
library(dplyr)
library(tidyr)

microbenchmark(ans.uwe = data.table(text = txt2)[, tstrsplit(text, ": ")
                                                 ][is.na(V2), Name := V1
                                                   ][, Name := zoo::na.locf(Name)
                                                     ][!is.na(V2), dcast(.SD, Name ~ V1, fun = toString, value.var = "V2")],
               ans.zx8754 = data_frame(txt = txt2) %>% 
                 mutate(txt = ifelse(grepl(":", txt), txt, paste("Name:", txt)),
                        rn = row_number()) %>% 
                 separate(txt, into = c("mytype", "mytext"), sep = ":") %>% 
                 spread(key = mytype, value = mytext) %>% 
                 select(-rn) %>% 
                 fill(Name) %>% 
                 group_by(Name) %>% 
                 fill(1:2, .direction = "down") %>% 
                 fill(1:2, .direction = "up") %>% 
                 unique() %>% 
                 ungroup() %>% 
                 select(3:1),
               ans.jaap = data.table(txt = txt2)[!grepl(':', txt), name := txt
                                                 ][, name := zoo::na.locf(name)
                                                   ][grepl('^Email:', txt), email := sub('Email: ','',txt)
                                                     ][grepl('^City/Town:', txt), city_town := sub('City/Town: ','',txt)
                                                       ][txt != name, lapply(.SD, function(x) toString(na.omit(x))), by = name, .SDcols = c('email','city_town')],
               ans.G.Grothendieck = {
                 L <- trimws(readLines(textConnection(txt2)))
                 ix <- !grepl(":", L)
                 L[ix] <- paste("\nName:", L[ix])
                 read.dcf(textConnection(L))},
               times = 1000)

Result:

Unit: microseconds
               expr       min         lq       mean     median        uq        max neval  cld
            ans.uwe  4243.754  4885.4765  5305.8688  5139.0580  5390.360  92604.820  1000   c 
         ans.zx8754 39683.911 41771.2925 43940.7646 43168.4870 45291.504 130965.088  1000    d
           ans.jaap  2153.521  2488.0665  2788.8250  2640.1580  2773.150  91862.177  1000  b  
 ans.G.Grothendieck   266.268   304.0415   332.6255   331.8375   349.797    721.261  1000 a   
zx8754
  • 52,746
  • 12
  • 114
  • 209
Axeman
  • 32,068
  • 8
  • 81
  • 94