【问题标题】:R - Extracting summary statistics for all columns in an xts object either directly or first converting to data frameR - 直接或首先转换为数据框提取 xts 对象中所有列的汇总统计信息
【发布时间】:2014-06-22 18:16:36
【问题描述】:

我有一个 xts 对象,其中包含 24 小时内的多个参数(每分钟测量一次)。根据时间,我添加了一列分组为 4 个“一天中的时间”(tod)选项:“早上”、“下午”、“晚上”和“晚上”。

我想提取整个时期以及一天中时间('tod')的列(参数)的平均值和标准差。

我曾尝试先将 xts 对象转换为数据框,但在列是类因子而不是数字时遇到了问题。我也尝试过“聚合”,但是当我使用聚合时,我得到了非常奇怪的输出(或错误)。这是一个例子:

例如用于创建更小的数据版本的代码:

# time vector:
Time <- ISOdatetime(2015,01,01,6,12,0) + seq(0:(0.5*60-1))*1*60

# sample parameter columns
a <- 1:30
b <- 31:60
c<-seq(1,90,3)

# a sample xts object 'tester'
tester <- xts(cbind(a,b,c),Time)

# assign 'time of day':
tester$tod <- NA
tester$tod["T06:00/T06:20"]<-"night"
tester$tod["T06:21/T11:30"]<-"morning"
tester$tod["T06:31/T06:50"]<-"afternoon"

例如,我如何尝试获取所有数据的 a、b、c 的平均值以及使用“聚合”的“tod”(请注意,我的数据中有 NA,但这不是问题):

tester$group = 1 #create a group column just to get the means for all data
mean_all <- aggregate(.~group, data=tester, FUN=mean, na.rm = TRUE, na.action=NULL)
meann_tod <- aggregate(.~tod, data=tester, FUN=mean, na.rm = TRUE, na.action=NULL)

不幸的是,这不起作用,虽然没有错误,但值完全错误。

任何建议都将不胜感激,我想这将是一项非常简单的任务!

【问题讨论】:

    标签: r dataframe aggregate xts


    【解决方案1】:

    当您尝试创建字符向量tod 时,您需要将 coredata 矩阵强制为字符而不是数字。当它基本上拒绝让你弄乱你的其他数据时,作者确实发出了警告,但你忽略了它(直到我做了一些额外的工作我才理解它。)你可以构造一个数字向量来进行分组:

    > tester$tod <- NA
    > tester$tod["T06:00/T06:20"]<-1
    > tester$tod["T06:21/T11:30"]<-2
    > tester$tod["T06:31/T06:50"]<-3
    > 
    > tester$group = 1 
    > (mean_all <- aggregate(.~group, data=tester, FUN=mean, na.rm = TRUE, na.action=NULL))
      group    a    b    c      tod
    1     1 15.5 45.5 44.5 2.133333
    > (meann_tod <- aggregate(.~tod, data=tester, FUN=mean, na.rm = TRUE, na.action=NULL))
      tod    a    b    c group
    1   1  4.5 34.5 11.5     1
    2   2 13.5 43.5 38.5     1
    3   3 24.5 54.5 71.5     1
    

    我可能会从公式中省略“组”变量:

    > (meann_tod <- aggregate(cbind(a,b,c)~tod, data=tester, FUN=mean, na.rm = TRUE, na.action=NULL))
      tod    a    b    c
    1   1  4.5 34.5 11.5
    2   2 13.5 43.5 38.5
    3   3 24.5 54.5 71.5
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-02-21
      • 2018-08-11
      • 2014-04-09
      • 2020-12-03
      • 1970-01-01
      • 2011-05-21
      • 2019-08-18
      • 2022-12-06
      相关资源
      最近更新 更多