【问题标题】:How can I average every 2n element of a list? [duplicate]如何平均列表的每 2n 个元素? [复制]
【发布时间】:2018-11-06 19:47:04
【问题描述】:

我有一个包含 86 个值的列表,其中列出的每两个值都是一个样本的结果。我正在测量 43 个样本。

例如(缩写)

   5.157
4.266
5.118
5.473
4.909
5.093

我正在努力得到这个最终结果

4.7115
5.2955
5.001

【问题讨论】:

标签: r list average


【解决方案1】:

我们使用gl 创建一个分组变量,并使用mean 分组

unname(tapply(v1,  as.integer(gl(length(v1), 2, length(v1))), FUN = mean))
#[1] 4.7115 5.2955 5.0010

数据

v1 <- c(5.157, 4.266, 5.118, 5.473, 4.909, 5.093)

【讨论】:

    【解决方案2】:

    另一种选择是添加索引列。

    library(tidyverse)
    
    #Sample data
    set.seed(123)
    df <- data.frame(x = rnorm(10, mean = 10, sd = 2))
    
    df %>% 
      mutate(index = rep(1:(nrow(df)/2), each = 2)) %>% 
      group_by(index) %>% 
      summarise(xMean = mean(x)) %>% 
      ungroup()
    

    输出:

      index xMean
      <int> <dbl>
    1     1  9.21
    2     2 11.6 
    3     3 11.8 
    4     4  9.20
    5     5  8.87
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-10-29
      • 1970-01-01
      • 2013-07-22
      • 2021-06-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多