我想读取数据以创建图。
我的源数据是:
["201801",111],["201802",222],["201803",333]
我想创建一个数据框,例如:
201801 111
201802 222
201803 333
我尝试使用
df <- read.table('fuel_data.txt',header=FALSE, sep = ",")
它不起作用,因为","
不仅用于分隔记录内的数据,而且还分隔不同的记录。有没有办法将这种数据读入数据帧?
谢谢!
答案 0 :(得分:2)
将每个[用换行符和每个]替换,并将逗号用空格替换,然后在其中读取:
txt <- '["201801",111],["201802",222],["201803",333]'
read.table(text = chartr("[],", "\n ", txt))
给予:
V1 V2
1 201801 111
2 201802 222
3 201803 333
答案 1 :(得分:2)
比G. Grothendieck的方法漂亮得多:
df <- readLines('fuel_data.txt')
df <- gsub("[", "", df, fixed = T)
# change ], for newlines
df <- gsub("],", "\n", df, fixed = T)
df <- gsub("]", "\n", df, fixed = T)
df <- read.table(textConnection(df), sep = ",")
df
# V1 V2
# 1 201801 111
# 2 201802 222
# 3 201803 333