2013-03-28 37 views
2

我是新来R. 我想改变这样的二元矩阵:
例如:每10列汇总二元矩阵的计算

" 1874 1875 1876 1877 1878 .... 2009 
F  1  0  0  0  0 ... 0 
E  1  1  0  0  0 ... 0 
D  1  1  0  0  0 ... 0 
C  1  1  0  0  0 ... 0 
B  1  1  0  0  0 ... 0 
A  1  1  0  0  0 ... 0" 

因为,列名来,我要汇总他们在几十年,并获得类似的东西:

"1840-1849 1850-1859 1860-1869 .... 2000-2009 
F  1  0  0  0  0 ... 0 
E  1  1  0  0  0 ... 0 
D  1  1  0  0  0 ... 0 
C  1  1  0  0  0 ... 0 
B  1  1  0  0  0 ... 0 
A  1  1  0  0  0 ... 0" 

我习惯了python,不知道如何做这个转换,而不做循环! 谢谢,伊莎贝尔

+1

什么是聚合函数?和?意思?也许让你的问题[reproducible](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example)? – Chase

+1

你如何将年份加总为一年,例如如果我在1840年到1849年间有一个“c(1,1,1,1,1,0,0,0,0,0)”的向量,结果是多少?最小值,最大值,模式,中位数? –

回答

2

你想要的聚合目前还不清楚,但使用下面的虚拟数据

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) 

然后,我们应用超过ind1:(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应用的功能。

+0

谢谢。我想要有1,如果在结果向量中(ex c(1,1,1,1,1,0,0,0,0,0))有任何1.也许使用max()。我会尝试你的建议。 – user2219894

+0

我的第二个例子讲述了,'as.numeric(rowSums(x)> 0)'实际上就是我在那里使用的,'max'只有在你知道数据只包含'1'和'0' 'max'可能比'rowSums'版本更有效率,但你需要'apply(x,1,max)',即对每行应用'max'。 –

+0

@GavinSimpson'out'中的值不需要对应于您生成的示例数据 –

1

这是另一种选择,使用模块化算法来聚合列。

# setup, borrowed from @GavinSimpson 
set.seed(42) 
df <- data.frame(matrix(sample(0:1, 6*25, replace = TRUE), ncol = 25)) 
names(df) <- 1874 + 0:24 

result <- do.call(cbind, 
    by(t(df), as.numeric(names(df)) %/% 10 * 10, colSums)) 

# add -xxx9 to column names, for each decade 
dimnames(result)[[2]] <- paste(colnames(result), as.numeric(colnames(result)) + 9, sep='-') 

# 1870-1879 1880-1889 1890-1899 
# V1   4   5   6 
# V2   4   6   6 
# V3   2   5   5 
# V4   5   5   7 
# V5   3   3   7 
# V6   5   5   4 

如果你想比sum其他东西聚集,东西替代呼叫 colSumsfunction(cols) lapply(cols, f),其中f是凝聚 功能,例如max