本文介绍了R,如何使用R数据帧中的相同日期字段聚合数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个R数据框,如下所示:

  SURVEY.DATE ABC 
1898 2010- 05-13 38 34 21
1899 2010-05-13 38 33 21
1897 2010-05-14 37 34 21
1895 2010-05-21 38 29 21
1896 2010-05-21 39 32 21
1894 2010-05-23 39 32 21

我想平均排列相同的日期,所以每天只有一个平均观察。理想情况下,我想最终得到一个如下的xts obsject:

  SURVEY.DATE ABC 
1898 2010 -05-13 38 33.5 21
1897 2010-05-14 37 34 21
1896 2010-05-21 38.5 30.5 21
1894 2010-05-23 39 32 21

似乎是我新手R技能的挑战...任何帮助/指针将不胜感激

解决方案

以下是使用 data.table b
$ b

  require(data.table)
setDT(df)[,lapply(.SD,mean),by = SURVEY.DATE]
#SURVEY.DATE ABC
#1:2010-05-13 38.0 33.5 21
#2:2010-05-14 37.0 34.0 21
#3:2010-05-21 38.5 30.5 21
#4:2010-05-23 39.0 32.0 21

检查新的HTML小插曲。


Hi I have an R dataframe that looks like the following:

        SURVEY.DATE A   B   C
1898    2010-05-13  38  34  21
1899    2010-05-13  38  33  21
1897    2010-05-14  37  34  21
1895    2010-05-21  38  29  21
1896    2010-05-21  39  32  21
1894    2010-05-23  39  32  21

I would like to average the rows with the same date so to have only one average observation per day. Ideally I would like to end up with an xts obsject that would look like :

        SURVEY.DATE    A      B  C
1898    2010-05-13    38   33.5 21
1897    2010-05-14    37     34 21
1896    2010-05-21  38.5   30.5 21
1894    2010-05-23    39     32 21

Seems to be a challenge for my newbie R skills...any help / pointers would be appreciated

解决方案

Here's how I'd do this using data.table.

require(data.table)
setDT(df)[, lapply(.SD, mean), by=SURVEY.DATE]
#    SURVEY.DATE    A    B  C
# 1:  2010-05-13 38.0 33.5 21
# 2:  2010-05-14 37.0 34.0 21
# 3:  2010-05-21 38.5 30.5 21
# 4:  2010-05-23 39.0 32.0 21

Check the new HTML vignettes if you'd like to learn more.

这篇关于R,如何使用R数据帧中的相同日期字段聚合数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 21:48