如何处理杂乱的原始数据并将其导入 R?

How do I wrangle messy, raw data and import into R?

我有原始的、混乱的时间序列数据,包含大约 1400 个观察值。这是它的样子的片段:

[new Date('2021-08-24'),1.67,1.68,0.9,null],[new Date('2021-08-23'),1.65,1.68,0.9,null],[new Date('2021-08-22'),1.62,1.68,0.9,null] ... etc

我想提取日期及其各自的值以在 R 中形成一个 tsibble。因此,从上述值来看,它就像

Date y-variable
2021-08-24 1.67
2021-08-23 1.65
2021-08-22 1.62

请注意如何只有第一个值与其各自的日期配对 - 我不需要其他值。现在,原始数据已被复制并粘贴到 word 文档中,我不确定如何处理数据整理以导入 R。

我怎样才能做到这一点?

#replace the text conncetion with a file connection if desired, the file should be a txt then
input <- readLines(textConnection("[new Date('2021-08-24'),1.67,1.68,0.9,null],[new Date('2021-08-23'),1.65,1.68,0.9,null],[new Date('2021-08-22'),1.62,1.68,0.9,null]"))

#insert line breaks
input <- gsub("],[", "\n", input, fixed = TRUE)

#remove "new Date"
input <- gsub("new Date", "", input, fixed = TRUE)

#remove parentheses and brackets
input <- gsub("[\(\)\[\]]", "", input, perl = TRUE)

#import cleaned data
DF <- read.csv(text = input, header = FALSE, quote = "'")
DF$V1 <- as.Date(DF$V1)
print(DF)
#          V1   V2   V3  V4   V5
#1 2021-08-24 1.67 1.68 0.9 null
#2 2021-08-23 1.65 1.68 0.9 null
#3 2021-08-22 1.62 1.68 0.9 null

这个怎么样?

text <- "[new Date('2021-08-24'),1.67,1.68,0.9,null],[new Date('2021-08-23'),1.65,1.68,0.9,null],[new Date('2021-08-22'),1.62,1.68,0.9,null]"

df <- read.table(text = unlist(strsplit(gsub('new Date\(|\)', '', gsub('^.(.*).$', '\1', text)), "].\[")), sep = ",")

> df
          V1   V2   V3  V4   V5
1 2021-08-24 1.67 1.68 0.9 null
2 2021-08-23 1.65 1.68 0.9 null
3 2021-08-22 1.62 1.68 0.9 null

从这一点来看,更改列名和删除最后一列是微不足道的