以与访问矩阵元素相同的方式访问列表元素

Access an element of a list in the same manner how you access an element of a matrix

我有一个矩阵:

mat <- matrix(c(3,9,5,1,-2,8), nrow = 2)

     [,1] [,2] [,3]
[1,]    3    5   -2
[2,]    9    1    8

我有一个列表:

lst <- as.list(data.frame(matrix(c(3,9,5,1,-2,8), nrow = 2)))

$X1
[1] 3 9

$X2
[1] 5 1

$X3
[1] -2  8

我可以通过 mat[i,j] 访问我的矩阵 我可以访问我的列表 lst[[c(i,j)]]

但是如果在矩阵中,如果我这样做 mat[1,2],我会得到 5。如果我在列表中使用相同的数字 lst[[c(1,2)]],我会得到 9。

有什么方法可以让我在访问列表时获得相同的号码?也许以某种方式操纵列表?当我使用 lst[[c(1,2)]] 时,我想得到 5 而不是 9。我想得到与使用 mat[i,j] 时相同的数字。

您可以使用 purrr 中的 transpose() 来转置列表。

lst2 <- purrr::transpose(lst)

lst2[[c(1,2)]]
# [1] 5

你可以试试

> list2DF(lst)[1, 2]
[1] 5