如何重复减去R中数据矩阵的行
问题描述:
我有一个1000×2的矩阵,如下所示:
I have a 1000×2 matrix as follows:
A B
Row1 0 2
Row2 0 3
Row3 0 4
Row4 0 5
Row5 0 3
Row6 0 4
...
...
Row999 0 8
Row1000 0 9
我想向矩阵添加一个新的列C.新列C的元素是通过计算列B的连续块之和的比率获得的.每个块包含两个元素.换句话说,我想得到以下矩阵:
I want to add a new column C to the matrix. The elements of the new column C are obtained by calculating the ratios of the sum of consecutive blocks of Column B. Each block contains two elements. In other words, I want to get the following matrix:
A B C
Row1 0 2 2/(2+3)
Row2 0 3 3/(2+3)
Row3 0 4 4/(4+5)
Row4 0 5 5/(4+5)
Row5 0 3 3/(3+4)
Row6 0 4 4/(3+4)
...
...
Row999 0 8 8/(8+9)
Row1000 0 9 9/(8+9)
我不知道如何在R中执行此操作.有人可以帮助我吗?非常感谢你. (对不起,我的英语表达不好,我不是母语人士.)
I don't know how to do this in R. Could anyone help me with this? Thank you very much. (Sorry for my poor English expression, I am not a native speaker.)
答
如果m
是矩阵,您似乎想对两个元素的连续块求和,就可以做到:
You seem to wanna sum consecutive blocks of two elements, and you can do, if m
is your matrix:
library(zoo)
cbind(m, m[,2]/rep(rollapply(m[,2], 2, sum, by=2), each=2))
或基于R
:
x = m[,2][!!seq(nrow(m))%% 2] + m[,2][!seq(nrow(m))%% 2]
cbind(m, rep(x, each=2))