粘贴具有R中特定范围的矩阵列

时间:2013-09-07 04:06:24

标签: r

假设我有一个矩阵:

 a=matrix(1:30,5)

我想将列3乘以3粘贴以获得此结果:

                [,1]                  [,2]
[1,]    "1     6    11"    "16   21   26"
[2,]   " 2     7    12"    "17   22   27"
[3,]   " 3     8    13"    "18   23   28"
[4,]    "4     9    14"    "19   24   29"
[5,]   " 5   10   15"   " 20   25   30"

事实上,我需要一个非常大的矩阵函数。

举个简单示例,我们可以使用whitinpastepaste several column values into one value in R)。

1 个答案:

答案 0 :(得分:2)

试试这个:

> g <- rep(1:2, each = 3)
> t(apply(a, 1, tapply, g, paste, collapse = " "))
     1         2         
[1,] "1 6 11"  "16 21 26"
[2,] "2 7 12"  "17 22 27"
[3,] "3 8 13"  "18 23 28"
[4,] "4 9 14"  "19 24 29"
[5,] "5 10 15" "20 25 30"