根据来自不同列的位置计算数据框中的平均值

Calculating an average in a data frame based on locations from separate columns

我有一个像这样设置的数据框:

N1 <- c(1,2,4,3,2,3,4,5,4,3,4,5,4,5,6,8,9)
Start <- c("","Start","","","","","","","Start","","","","Start","","","","")
Stop <- c("","","","","Stop","","","","","","Stop","","","","Stop","","")

N1 是我感兴趣的数据。我想根据接下来两列中的 "Start" 和 "Stop" 位置计算一串数字的平均值。

"Start" 和 "Stop" 定义的字符串如下所示:

2,4,3,2 
4,3,4
4,5,6

所以我的最终结果应该是3表示:

    2.75,3.6,5

你可以试试:

mapply(function(start, stop){
          mean(N1[start:stop])
       }, 
       start=which(Start!=""), 
       stop=which(Stop!=""))

#[1] 2.750000 3.666667 5.000000

你也可以试试rollapply

library(zoo)
x <- sort(c(which(Stop != ""), which(Start != ""))) # indices of Start and Stop
rollapply(x, 2, FUN = function(y) mean(N1[y[1]:y[2]]), by=2)
[1] 2.750000 3.666667 5.000000
library(data.table) # need latest 1.9.5+

# set up data to have all 1's column for the period we're interested in and 0 otherwise
d = data.table(N1, event = cumsum((Start != "") - c(0, head(Stop != "", -1))))

d[, mean(N1), by = .(event, rleid(event))][event == 1, V1]
#[1] 2.750000 3.666667 5.000000

# or equivalently
d[, .(event[1], mean(N1)), by = rleid(event)][V1 == 1, V2]