【问题标题】:How do I wrangle messy, raw data and import into R?如何处理凌乱的原始数据并导入 R?
【发布时间】:2021-10-30 20:45:15
【问题描述】:

我有包含大约 1400 个观察值的时间序列的原始、混乱数据。这是它的外观的 sn-p:

[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。

我怎样才能做到这一点?

【问题讨论】:

  • 如果您创建一个小的可重现示例以及预期的输出,这将更容易提供帮助。阅读how to give a reproducible example
  • 我假设输入不包含换行符。这些只是在对问题的编辑中添加的。如果它们存在,我的答案中的代码可以很容易地调整。

标签: r import time-series data-wrangling raw-data


【解决方案1】:
#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

【讨论】:

    【解决方案2】:

    这是怎么回事?

    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
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-09-27
      • 2018-05-02
      • 2016-10-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多