【问题标题】:times series import from Excel and date manipulation in R从 Excel 导入时间序列和 R 中的日期操作
【发布时间】:2013-10-28 19:41:23
【问题描述】:

我在 .csv excel 文件中有 2 列时间序列,“日期”和“小部件”

我将文件导入 R 使用:

widgets<-read.csv("C:things.csv")
str(things)

'data.frame':   280 obs. of  2 variables:
 $ date: Factor w/ 280 levels "2012-09-12","2012-09-13",..: 1 2 3 4 5 6 7 8 9 10 ...
 $ widgets  : int  5 10 15 20 30 35 40 50 55 60 65 70 75 80 85 90 95 100 ...

如何将因素 things$date 转换为 xts 或时间序列格式?

例如当我:

hist(things)
Error in hist.default(things) : 'x' must be numeric

【问题讨论】:

  • 当您致电read.csv 时,如果您不想将您的characters 变成factors,您可能想要stringsAsFactors = FALSE。如果要将character 转换为Date,请使用?as.Datethings$date &lt;- as.Date(as.character(things$date), format = "%Y-%m-%d") 应该在这里与您已有的 factor 一起使用。

标签: r time-series


【解决方案1】:

尝试将其作为动物园对象读入,然后转换:

Lines <- "date,widgets
2012-09-12,5
2012-09-13,10
"
library(zoo)
# replace first argument with:  file="C:things.csv"
z <- read.zoo(text = Lines, header = TRUE, sep = ",")
x <- as.xts(z)

【讨论】:

  • 如注释中所示,它可以是字符串或文本文件。见?read.zoo
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-17
  • 2015-04-03
  • 2015-01-03
  • 2019-09-10
  • 1970-01-01
相关资源
最近更新 更多