【问题标题】:R Calculate row average, different columns for each row as indicated by another columnR计算行平均值,每一行的不同列由另一列指示
【发布时间】:2021-02-11 02:09:59
【问题描述】:

我想计算每一行不同列的行平均值,如另一列所示。在这个示例数据帧中,列“number”的范围是 1:11,其他 12 列命名为“block_1”到“block_12”。例如,如果“block”为 5,我想计算列的行平均值块_6 到块_12。也就是说,通过block_12,在“number”列中指示的块号的平均值。每个 ID 代表一个唯一条目,应保留所有行。 我怎样才能做到这一点?

n <- 11 ; m <- 11 ; reps <- 12 
dff<-as.data.frame(cbind(matrix(sample.int(11, n, replace = TRUE), n, m/n), 
                    replicate(reps, sample(1:9, n, replace = TRUE)/10)))

myFun<- function(n = 5000) {
  a <- do.call(paste0, replicate(5, sample(LETTERS, n, TRUE), FALSE))
  paste0(a, sprintf("%04d", sample(9999, n, TRUE)), sample(LETTERS, n, TRUE))
}

dff$ID<-myFun(11)

dff<-data.table::setnames(dff, old = c('V1','V2','V3','V4', 'V5','V6','V7','V8','V9','V10', 'V11','V12','V13'), new = c('number','block_1','block_2','block_3','block_4', 'block_5','block_6','block_7','block_8','block_9','block_10', 'block_11','block_12'))

【问题讨论】:

    标签: r


    【解决方案1】:

    这是一个基本的 R 选项:

    cols <- grep('block', names(dff), value = TRUE)
    n <- length(cols)
    
    dff$mean_value <- mapply(function(x, y) mean(unlist(dff[x, cols[y:n]])), 
                             seq(nrow(dff)), dff$number + 1)
    

    【讨论】:

      猜你喜欢
      • 2016-09-02
      • 1970-01-01
      • 2022-01-05
      • 2019-04-03
      • 1970-01-01
      • 2014-03-15
      • 2020-04-02
      • 2023-03-27
      • 2020-06-01
      相关资源
      最近更新 更多