gpt4 book ai didi

arrays - 在R中按行和列从数据框中调用多个值

转载 作者:行者123 更新时间:2023-12-05 01:07:30 26 4
gpt4 key购买 nike

我在 R 中工作,我想通过列和行索引从数据框中调用一组值。然而,这样做会产生一个矩阵而不是一个数组。我将证明:

鉴于data.frame:

a = data.frame( a = array(c(1,2,3,4,5,6,7,8,9), c(3,3)) )

(对于那些不想插入它的人,它看起来像这样)
  a.1 a.2 a.3
1 1 4 7
2 2 5 8
3 3 6 9

假设我有两个数组指向我想要获取的值
grab_row = c(3,1,2)
grab_col = c(1,2,1)

现在我希望这是我想要的代码......
a[ grab_row, grab_col ]

为了得到这些结果...
[1] 3 4 2

但这是一个 3x3 矩阵,它本身就足够有意义
  a.1 a.2 a.1.1
3 3 6 3
1 1 4 1
2 2 5 2

好吧,我也看到我的答案在 3x3 矩阵的对角线上......但我真的宁愿坚持使用数组作为输出。

有什么想法吗?丹卡。

最佳答案

将行和列索引作为两列矩阵传入(此处使用 cbind() 构造)将获得您期望的元素:

a[cbind(grab_row, grab_col)]
[1] 3 4 2

这种形式的索引记录在 ?"[" 中。 :

Matrices and array:

[...snip...]

A third form of indexing is via a numeric matrix with the one column for each dimension: each row of the index matrix then selects a single element of the array, and the result is a vector.

关于arrays - 在R中按行和列从数据框中调用多个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18520818/

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