你想要的聚合目前还不清楚,但使用下面的虚拟数据
set.seed(42)
df <- data.frame(matrix(sample(0:1, 6*25, replace = TRUE), ncol = 25))
names(df) <- 1874 + 0:24
在每个10年期以下计数事件。
获取年的数值变量
years <- as.numeric(names(df))
接下来,我们需要为每一个十年开始的指示
ind <- seq(from = signif(years[1], 3), to = signif(tail(years, 1), 3), by = 10)
然后,我们应用超过ind
(1:(length(ind)-1)
)指数,选择列从当前十年的df
,并使用rowSums
来计数1
。
tmp <- lapply(seq_along(ind[-1]),
function(i, inds, data) {
rowSums(data[, names(data) %in% inds[i]:(inds[i+1]-1)])
}, inds = ind, data = df)
接下来我们cbind
得到的载体为数据帧和修复行动的列名:
out <- do.call(cbind.data.frame, tmp)
names(out) <- paste(head(ind, -1), tail(ind, -1) - 1, sep = "-")
out
这给:
> out
1870-1879 1880-1889 1890-1899
1 4 5 6
2 4 6 6
3 2 5 5
4 5 5 7
5 3 3 7
6 5 5 4
如果你想要一个简单的二元矩阵一个1
表示在该十年中至少发生了一件事,那么您可以使用:
tmp2 <- lapply(seq_along(ind[-1]),
function(i, inds, data) {
as.numeric(rowSums(data[, names(data) %in% inds[i]:(inds[i+1]-1)]) > 0)
}, inds = ind, data = df)
out2 <- do.call(cbind.data.frame, tmp2)
names(out2) <- paste(head(ind, -1), tail(ind, -1) - 1, sep = "-")
out2
这给:
> out2
1870-1879 1880-1889 1890-1899
1 1 1 1
2 1 1 1
3 1 1 1
4 1 1 1
5 1 1 1
6 1 1 1
如果你想有一个不同的聚合,然后修改lapply
呼叫使用其他的东西比rowSums
应用的功能。
什么是聚合函数?和?意思?也许让你的问题[reproducible](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example)? – Chase
你如何将年份加总为一年,例如如果我在1840年到1849年间有一个“c(1,1,1,1,1,0,0,0,0,0)”的向量,结果是多少?最小值,最大值,模式,中位数? –