Regex in R: parse content of 1-column dataframe


Keywords:r 


Question: 

Although I can't imagine it not having been asked before in one way or another, I don't seem to be able to find something that answers my question.

I have data that looks like this

> mydata1
V1
,10.00,20.00,30.00,40.00
,11.00,22.00,33.00,44.00

And I'd like to have data that looks like:

> mydata2
V1       V2      V3       V4
10.00    20.00   30.00    40.00
11.00    22.00   33.00    44.00

When I try read.table and separation with "," I get:

> mydata2 <- read.table(> mydata1, sep = ",")
Error in read.table(mydata1, sep = ",") : 
'file' must be a character string or connection

I tried some Regex magic, but this didn't work (mostly because I have no deep understanding in the matter).

Any help is much appreciated!


2 Answers: 

We can use read.csv after removing the , at the start of the string with sub

mydata2 <- read.csv(text = sub("^,", "", mydata1$V1), header = FALSE)
mydata2
#  V1 V2 V3 V4
#1 10 20 30 40
#2 11 22 33 44
 
library(tidyverse)
separate(mydata1, V1, into = c("V0", "V1", "V2", "V3", "V4"), sep = ",") %>% select(-V0)


#      V1    V2    V3    V4
# 1 10.00 20.00 30.00 40.00
# 2 11.00 22.00 33.00 44.00