gpt4 book ai didi

r - 使用索引的数据框从数据框中提取值 - R

转载 作者:行者123 更新时间:2023-12-02 08:17:25 35 4
gpt4 key购买 nike

我有一个有用信息的数据框:

X = c(1,2,3,4,5,6,7,8,9,10)
Y = c(5,4,3,2,1,0,1,2,3,4)
Z = c(11,12,13,14,15,16,17,18,19,20)

df <- data.frame(X, Y, Z)

还有一个行列位置的数据框:

row <- c(6,2,5)
column <- c(1,2,3)


pos <- data.frame(row, column)

我想使用一些函数(fun),它使用 pos 中的列和行位置来返回 df 中的值那些职位,例如

fun(df, pos$row, pos$column)
[1] 6 4 15

我以为我可以这样做,但无济于事

df[c(pos$row),c(pos$col)]

最佳答案

行/列索引作为 matrix 工作,因此我们将“pos”转换为 matrix 并将其用作行/列索引以提取值.

df[as.matrix(pos)]

否则,cbind 'pos' 的列作为 vectors 的 cbind 返回一个 matrix

df[cbind(pos$row, pos$column)]

这可以转化为函数

fExtract <- function(dat, indexDat){
dat[as.matrix(indexDat)]
}
fExtract(df, pos)
#[1] 6 4 15

关于r - 使用索引的数据框从数据框中提取值 - R,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40692736/

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