我们可以使用索引矩阵从 tibble 中检索条目吗?

问题描述 投票:0回答:1

我有一个矩阵,其中存储了我想要从数据集中检索的行索引和列索引。使用

data.frame
效果很好:

set.seed(1)
df <- data.frame(a= letters[1:10], b= LETTERS[1:10])
sm <- matrix(c(sample(1:10, 3, replace= TRUE), sample(1:2, 3, replace= TRUE)), ncol= 2)
df[sm]
[1] "i" "D" "g"

但是使用相同的索引矩阵从

tibble
获取条目会失败:

df_tibble <- tibble::as_tibble(df)
df_tibble[sm]

这会返回错误

Error in df_tibble[sm]: ! Subscript sm is a matrix, it must be of type logical. Run rlang::last_trace() to see where the error occurred.

如何使用

sm
df[sm]
获取条目
df_tibble
? 到目前为止我想到的只是
as.data.frame(df_tibble)[sm]
。那么这是否意味着我们不能用索引矩阵对
tibble
进行子集化,而必须先转移到
data.frame

r dataframe matrix subset tibble
1个回答
1
投票

使用 unlist() 的解决方法:

pull_tbl_from_mat <- function(tbl, sm) {
  n <- nrow(tbl)
  unlist(tbl, use.names = FALSE)[sm[, 1L] + (sm[, 2L] - 1L) * n]
}

foo(df_tibble, sm)
# [1] "i" "D" "g"
© www.soinside.com 2019 - 2024. All rights reserved.