English 中文(简体)
R中表格中每一栏的相邻列列和相邻列列总和
原标题:sum adjacent columns for each column in a matrix in R
  • 时间:2012-05-22 06:40:06
  •  标签:
  • r
  • matrix
  • diff

I am trying to get a function that is the opposite of diff() I want to add the values of adjacent columns in a matrix for each column in the matrix. I do NOT need the sum of the entire column or row. For example:

如果我说:

[ 1  2  4;
  3  5  8 ]

我最后会与:

[ 3  6;
  8  13 ]

当然,只要一两栏,这很简单,因为我可以做 x[,1,1]+x[,2],但这些矩阵相当大。

我感到惊讶的是,我似乎无法找到有效办法这样做。

问题回答
m <- matrix(c(1,3,2,5,4,8), nrow=2)
m[,-1] + m[,-ncol(m)]

     [,1] [,2]
[1,]    3    6
[2,]    8   13

或只是为了取乐

n <- ncol(m)
x <- suppressWarnings(matrix(c(1, 1, rep(0, n-1)), 
                             nrow = n, ncol = n-1))
m %*% x

     [,1] [,2]
[1,]    3    6
[2,]    8   13

虚数据数据

mat <- matrix(sample(0:9, 100, replace = TRUE), nrow = 10)

解决方案 :

sum.mat <- lapply(1:(ncol(mat)-1), function(i) mat[,i] + mat[,i+1])
sum.mat <- matrix(unlist(sum.mat), byrow = FALSE, nrow = nrow(mat))

您可以使用:

m <- matrix(c(1,2,4,3,5,8), nrow=2, byrow=T)
sapply(2:ncol(m), function(x) m[,x] + m[,(x-1)])




相关问题
XML Diff: How to generate XML diff using XSLT?

I would like to compute the diff between two XML files or nodes using XSL/XSLT. Is there any stylesheet readily available or any simple way of doing it?

diff/merge tool for TortoiseSVN within Visual Studio

We ve recently "upgraded" from Visual SourceSafe to SVN based on recommendations on this site. Our current source control set-up is: TortoiseSVN with VisualSVN. We re very happy with it so far, but I ...

How do I get each comp result?

I would like to check diffs and when files are not same,stop compare files. Compare any files C:/UML/reports/* and C:/UML/Test/*. In this two directory has same file names and also aim is to want to ...

Find differences between 2 HTML files

Is there a way to display differences between two HTML documents? There is a PHP class called daisdiff, but it has no documentation. Can anyone show how to use it, or any alternative?

How to specify different --strip (-p) levels for patch?

If I have a diff that has paths like these: --- a/b/foo/bar/baz.pl +++ c/foo/bar/baz.pl Is there a way to tell the patch utility that the diff roots are at different levels? i.e. -p2 for one, yet -...

热门标签