我有一个矩阵列表,每个矩阵都有相同数量的列。我想创建一个单一的数据框,其中包含来自matrix1的第一列,后跟来自matrix2的第一列,然后是来自matrix3的第一列...然后是来自matrix1的第二列,后跟来自matrix2的第二列等等。
counts <- data.frame(apples=round(rnorm(10, mean=5), digits=0),
oranges=round(rnorm(10, mean=5), digits=0),
pears=round(rnorm(10, mean=5), digits=0))
weights <- data.frame(apples=round(rnorm(10, mean=3), digits=1),
oranges=round(rnorm(10, mean=3), digits=1),
pears=round(rnorm(10, mean=3), digits=1))
diameters <- data.frame(apples=round(rnorm(10, mean=10), digits=1),
oranges=round(rnorm(10, mean=10), digits=1),
pears=round(rnorm(10, mean=10), digits=1))
fruitdata <- list(counts, weights, diameters)
> fruitdata
[[1]]
apples oranges pears
1 4 4 4
2 6 5 5
3 6 4 6
4 6 5 4
5 7 4 5
6 6 7 5
7 4 6 5
8 4 6 5
9 4 5 5
10 5 7 5
[[2]]
apples oranges pears
1 2.5 3.1 1.1
2 4.3 2.4 4.2
3 2.8 3.5 1.3
4 2.8 1.5 2.5
5 2.9 3.3 1.9
6 3.7 1.5 2.2
7 2.9 2.7 5.1
8 3.0 2.5 3.0
9 2.3 2.3 1.7
10 2.7 2.9 1.4
[[3]]
apples oranges pears
1 10.5 10.4 12.3
2 10.0 9.8 10.1
3 9.7 11.1 10.5
4 9.1 10.9 9.9
5 8.5 9.4 9.7
6 8.9 12.2 10.0
7 11.0 9.7 10.8
8 9.4 8.6 12.1
9 8.6 9.9 11.0
10 11.9 10.2 11.2
我希望你能为我提供类似于以下内容的翻译:
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 4 2.5 10.5 4 3.1 10.4
[2,] 6 4.3 10.0 5 2.4 9.8
[3,] 6 2.8 9.7 4 3.5 11.1
[4,] 6 2.8 9.1 5 1.5 10.9
[5,] 7 2.9 8.5 4 3.3 9.4
[6,] 6 3.7 8.9 7 1.5 12.2
[7,] 4 2.9 11.0 6 2.7 9.7
[8,] 4 3.0 9.4 6 2.5 8.6
[9,] 4 2.3 8.6 5 2.3 9.9
[10,] 5 2.7 11.9 7 2.9 10.2
我可以使用sapply从每个矩阵中提取第一列:
test1 <- sapply(fruitdata, function(x) x[,1])
> test1
[,1] [,2] [,3]
[1,] 4 2.5 10.5
[2,] 6 4.3 10.0
[3,] 6 2.8 9.7
[4,] 6 2.8 9.1
[5,] 7 2.9 8.5
[6,] 6 3.7 8.9
[7,] 4 2.9 11.0
[8,] 4 3.0 9.4
[9,] 4 2.3 8.6
[10,] 5 2.7 11.9
所以我尝试了:
test2 <- sapply(fruitdata, function(x) x[,1:ncol(fruitdata[[1]])])
但是它没有给我想要的东西。
>test2
[,1] [,2] [,3]
apples Numeric,10 Numeric,10 Numeric,10
oranges Numeric,10 Numeric,10 Numeric,10
pears Numeric,10 Numeric,10 Numeric,10
当然,我可以使用for循环来完成这个任务,但似乎应该能够使用apply或plyr套件来完成,但我还不能完全弄清楚如何做到这一点。
谢谢!
do.call(cbind, fruitdata)[order(rep(1:3, 3))]
来获取它,那么其中的 1:9 部分是什么意思? - rawr