多列的R时间聚合

时间:2018-01-15 15:44:24

标签: r time aggregate

我添加了一个数据框,其中包含一个时间和6个数据列,如下所示......

df <- data.frame(structure(list(Time = c(100, 100.1, 100.2, 100.2, 100.3, 100.3,100.3, 100.4, 100.4, 100.5, 100.5, 100.6, 100.6, 100.7),
               x = c(4,NA, 7, NA, 3, 7, NA, 9, NA, 7, NA, 3, NA, 7),
               y = c(NA, 7, NA,9, NA, 9, 7, NA, NA, NA, 9, NA, 5, NA), 
               a = c(7, NA, 3, 3, NA,NA, 7, NA, NA, 7, 7, NA, NA, 9),
               b = c(8, NA, 4, NA, 5, 4, NA,9, NA, 1, NA, 7, NA, 2),
               j = c(NA, 4, NA, 6, NA, 6, 4, NA, NA, NA, 6, NA, 2, NA), 
               k = c(1, NA, 5, 5, NA, NA, 1, NA, NA, 2, 2,NA, NA, 6)), 
          .Names = c("Time", "x", "a", "j", "y", "b", "k"), 
          class = c("tbl_df","tbl", "data.frame"), row.names = c(NA, -14L)))


Time    x   y   a   b   j   k
100     4   NA  7   8   NA  1
100.1   NA  7   NA  NA  4   NA
100.2   7   NA  3   4   NA  5
100.2   NA  9   3   NA  6   5
100.3   3   NA  NA  5   NA  NA
100.3   7   9   NA  4   6   NA
100.3   NA  7   7   NA  4   1
100.4   9   NA  NA  9   NA  NA
100.4   NA  NA  NA  NA  NA  NA
100.5   7   NA  7   1   NA  2
100.5   NA  9   7   NA  6   2
100.6   3   NA  NA  7   NA  NA
100.6   NA  5   NA  NA  2   NA
100.7   7   NA  9   2   NA  6

我想使用时间列进行聚合。必须在x和y,a和b,j和k之间计算时间平均值。输出应该看起来像这样..

Time    xy_mean ab_mean jk_mean
100         
100.1           
100.2           
100.3           
100.4           
100.5           
100.6           
100.7           

请帮助......

(如果问题不明确,请发表评论)

2 个答案:

答案 0 :(得分:3)

修改

基于@Marijn Stevering的评论,这种方法会更有效:

 df_final <- df %>% 
    group_by(Time) %>% 
   summarize(av_xy = mean(c(x,y), na.rm = TRUE), 
   av_ab = mean(c(a,b), na.rm = TRUE), 
   av_jk = mean(c(j,k), na.rm = TRUE))


df_final
## A tibble: 8 x 4
#   Time av_xy av_ab av_jk
#  <dbl> <dbl> <dbl> <dbl>
#1 100.0  6.00   NaN   4.0
#2 100.1   NaN   5.5   NaN
#3 100.2  5.50   7.5   4.0
#4 100.3  4.75   6.5   4.0
#5 100.4  9.00   NaN   NaN
#6 100.5  4.00   7.5   4.5
#7 100.6  5.00   3.5   NaN
#8 100.7  4.50   NaN   7.5

Original Anwser

我知道必须有更直接的东西,但这里有dplyr方法,但有一些步骤:

library(dplyr)

df_xy <- df %>%
      group_by(Time) %>%
      summarise(av_xy = mean(c(x,y), na.rm = TRUE))

df_ab <- df %>%
      group_by(Time) %>%
      summarise(av_ab = mean(c(a,b), na.rm = TRUE))

df_jk <- df %>%
      group_by(Time) %>%
      summarise(av_jk = mean(c(j,k), na.rm = TRUE))

df_final <- df_xy %>%
  left_join(df_ab) %>%
  left_join(df_jk)

 df_final
## A tibble: 8 x 4
#   Time av_xy av_ab av_jk
#  <dbl> <dbl> <dbl> <dbl>
#1 100.0  6.00   NaN   4.0
#2 100.1   NaN   5.5   NaN
#3 100.2  5.50   7.5   4.0
#4 100.3  4.75   6.5   4.0
#5 100.4  9.00   NaN   NaN
#6 100.5  4.00   7.5   4.5
#7 100.6  5.00   3.5   NaN
#8 100.7  4.50   NaN   7.5

答案 1 :(得分:2)

以下代码可以满足您的需求。它并不漂亮,它使用split将data.frame分割为子{d},然后连续Time来计算结果。
如果您要删除*apply值,请在代码的开头设置NA

NA.RM <- TRUE