Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read txt file with multiple separators

Tags:

dataframe

r

I want to read the data to create a plot.

My source data is:

["201801",111],["201802",222],["201803",333]

I want to create a dataframe like:

201801 111

201802 222

201803 333

I tried to use

df <- read.table('fuel_data.txt',header=FALSE, sep = ",")

It doesn't work because "," is not only used to separate data inside record but also separate different records. Is there a way to read this kind of data into a data frame?

Thanks!

like image 251
Dehua Liu Avatar asked Nov 28 '25 02:11

Dehua Liu


1 Answers

Replace each [ with a newline and each ] and comma with a space and then read it in:

txt <- '["201801",111],["201802",222],["201803",333]'
read.table(text = chartr("[],", "\n  ", txt))

giving:

      V1  V2
1 201801 111
2 201802 222
3 201803 333
like image 87
G. Grothendieck Avatar answered Nov 29 '25 16:11

G. Grothendieck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!