gpt4 book ai didi

r - 从数据框列表中按顺序提取每一列

转载 作者:行者123 更新时间:2023-12-04 10:52:34 25 4
gpt4 key购买 nike

我有一个矩阵列表,每个矩阵都有相同的列数。我想创建一个数据框,其中第一列来自 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 套件来完成它,但我不太清楚如何去做。

谢谢!

最佳答案

编辑:采纳了 rawr 的聪明建议。

这是你想要的吗?

do.call(cbind, fruitdata)[order(rep(1:3, 3))]

# apples apples.1 apples.2 oranges oranges.1 oranges.2 pears pears.1 pears.2
# 1 4 3.2 10.1 6 4.9 10.0 4 2.6 10.8
# 2 6 4.3 10.0 4 4.2 8.4 4 3.7 9.4
# 3 5 2.9 9.4 4 4.4 8.7 5 5.5 9.2
# 4 6 2.8 12.6 6 1.9 10.4 5 1.9 11.0
# 5 8 3.6 9.5 6 3.8 9.7 4 3.7 8.9
# 6 4 4.3 10.1 4 2.3 9.7 5 4.1 10.5
# 7 5 2.1 10.2 4 3.2 8.7 6 0.9 10.6
# 8 4 4.2 9.8 7 5.0 10.0 5 2.0 9.2
# 9 4 4.1 10.5 6 1.8 8.2 6 3.2 9.1
# 10 6 2.4 9.3 5 3.1 8.6 4 3.6 10.5

在这里,我们只是将所有矩阵粘在一起,然后对列重新排序,以便它们以您想要的方式结束。

关于r - 从数据框列表中按顺序提取每一列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21789512/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com