Break headers and data to separate fields

Viewed 36

I have this data that don't know how to break it to different fields

HeaderA.HeaderB.HeaderC
1A,1B,1C
2A,2B,2C

Data is read through csv file. I tried something like

cSplit(data, "HeaderA", ",") 

but it didn't work well. It gave me back the result as below without header. The data didn't even separate out to field correctly

"A1" "B1"     "C1"
"A2" "B2"     "C2"

My goal is to have data like:

HeaderA HeaderB HeaderC
1A      1B      1C
2A      2B      2C

Can somebody help please?

1 Answers

One option is a two-step read process: first parse the column names (with entries separated by "."), then read the main data (with entries separated by ","). We can roll this up into a custom my_read_data function.

my_read_data <- function(file) {
    
    # Read round 1: reads & splits column names
    data <- readr::read_delim(file, delim = ".", n_max = 0)

    # Read round 2: read data 
    dplyr::bind_rows(
        data, readr::read_csv(file, skip = 1, col_names = names(data)))

}

Then for the sample data you give, we have

library(dplyr)
library(readr)
my_read_data("HeaderA.HeaderB.HeaderC
1A,1B,1C
2A,2B,2C")
## A tibble: 2 × 3
#  HeaderA HeaderB HeaderC
#  <chr>   <chr>   <chr>  
#1 1A      1B      1C     
#2 2A      2B      2C     

This will also work if you replace sample data with a filename.

Related