合并具有相同列名的矩阵中的列 [英] Combine columns in matrix having same column name

查看:148
本文介绍了合并具有相同列名的矩阵中的列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个矩阵,其中的列重复字符列名称。

I have a matrix with columns that duplicate character column names.

set.seed(1)
m <- matrix(sample(1:10,12,replace=TRUE), nrow = 3, ncol = 4, byrow = TRUE,
       dimnames = list(c("s1", "s2", "s3"),c("x", "y","x","y")))

m
   x y  x  y
s1 3 4  6 10
s2 3 9 10  7
s3 7 1  3  2

我需要将具有相同列名的所有列加总为一个列,即

I need to sum all columns with the same column name into only one column i.e.

m <- matrix(c(9,14,13,16,10,3), nrow = 3, ncol = , byrow = TRUE,dimnames = list(c("s1", "s2", "s3"),c("x", "y")))

    x  y
s1  9 14
s2 13 16
s3 10  3

我在汇总函数中玩过简单的和,但是没有任何运气。有什么建议吗?谢谢。

I have had a play with the simple sum in the aggregate function but haven't had any luck. Any advice? Thanks.

推荐答案

好吧,此解决方案不会因代码透明性而获得任何奖项,但我更喜欢它:

Well, this solution won't win any awards for transparency of code, but I rather like it:

nms <- colnames(m)
m %*% sapply(unique(nms),"==", nms)
#     x  y
# s1  9 14
# s2 13 16
# s3 10  3






它的工作原理是构建一个矩阵,该矩阵形成 m 列的适当线性组合。若要查看其工作原理,请将第二行分成两个分量矩阵,使用%*%相乘,如下所示:


It works by constructing a matrix that forms appropriate linear combinations of m's columns. To see how it works, pick apart the second line into its two component matrices, which are multiplied together using %*%, like this:

 -          -      -   -
|  3 4  6 10 |    | 1 0 |
|  3 9 10  7 |    | 0 1 |
|  7 1  3  2 |    | 1 0 |
 -          -     | 0 1 |
                   -   -

这篇关于合并具有相同列名的矩阵中的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆