gpt4 book ai didi

r - 如何将 2D 数据框转换为 3D 矩阵,保留行和列顺序

转载 作者:行者123 更新时间:2023-12-04 11:44:08 32 4
gpt4 key购买 nike

我想将 2D 数据框转换为 3D 矩阵,同时保留行和列顺序。

我有一些这样的数据:

dat<-  data.frame(obs = rep(1:3,2),
LET=c('A','A','A','B','B','B'),
x1=c('a','b','c','d','e','f'),
x2=c('g','h','i','j','k','l'))
obs LET x1 x2
1 1 A a g
2 2 A b h
3 3 A c i
4 1 B d j
5 2 B e k
6 3 B f l

我想创建一个 3D 矩阵,输出如下所示:

, , 1

[,1] [,2] [,3] [,4]
[1,] "1" "A" "a" "g"
[2,] "1" "B" "d" "j"

, , 2

[,1] [,2] [,3] [,4]
[1,] "2" "A" "b" "h"
[2,] "2" "B" "e" "k"

, , 3

[,1] [,2] [,3] [,4]
[1,] "3" "A" "c" "i"
[2,] "3" "B" "f" "l"

每个“层”都是不同的 obs两个LET s 和它们的 x 值。当我做 dim(dat) <- c(2,4,3)订单没有按照我希望的方式保存,我不确定如何调整它以获得正确的格式。

最佳答案

一个选项是将数据拆分到一个列表,创建一个array指定的dimensions并赋值list 的值

lst1 <- split(dat, dat$obs)
ar1 <- array(dim = c(dim(lst1[[1]]), length(lst1)))
for(i in seq_along(lst1)) ar1[,,i] <- as.matrix(lst1[[i]])
ar1
#, , 1

# [,1] [,2] [,3] [,4]
#[1,] "1" "A" "a" "g"
#[2,] "1" "B" "d" "j"

#, , 2

# [,1] [,2] [,3] [,4]
#[1,] "2" "A" "b" "h"
#[2,] "2" "B" "e" "k"

#, , 3

# [,1] [,2] [,3] [,4]
#[1,] "3" "A" "c" "i"
#[2,] "3" "B" "f" "l"

或将所有列转换为character 类,执行splitunlist list 并创建数组

dat[] <- lapply(dat, as.character)
lst1 <- split(dat, dat$obs)
array(unlist(lst1), c(dim(lst1[[1]]), length(lst1)))

关于r - 如何将 2D 数据框转换为 3D 矩阵,保留行和列顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59567799/

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