我有一个数据框架设置如下:
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”定义的字符串如下所示:
2,4,3,2
4,3,4
4,5,6所以我的最终结果应该是3种方法:
2.75,3.6,5发布于 2015-04-21 09:14:05
你可以试试:
mapply(function(start, stop){
mean(N1[start:stop])
},
start=which(Start!=""),
stop=which(Stop!=""))
#[1] 2.750000 3.666667 5.000000发布于 2015-04-21 10:12:23
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]发布于 2015-04-21 09:40:29
您也可以尝试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.000000https://stackoverflow.com/questions/29767697
复制相似问题