取得具有(row,col)索引序列的data.table slice [英] Taking a data.table slice with a sequence of (row,col) indices

查看:195
本文介绍了取得具有(row,col)索引序列的data.table slice的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个data.table与下面的类似.

I have a data.table that resembles the one below.

tab <- data.table(a = c(NA, 42190, NA), b = c(42190, 42190, NA), c = c(40570, 42190, NA))
tab
       a     b     c
1:    NA 42190 40570
2: 42190 42190 42190
3:    NA    NA    NA

根据行索引向量和列索引向量的规范,我希望返回一个包含tab中与指定的行索引和列索引向量相对应的点的向量.

Upon specification of a vector of row indices, and a vector of column indices, I would like a vector returned containing the points in tab corresponding to the specified vector of row indices and column indices.

例如,假设我想在tab中获得对角线元素.我将指定两个向量

For example, suppose I wanted to get the diagonal elements in tab. I would specify two vectors,

ri <- 1:3
ci <- 1:3

和某些函数function(ri, ci, tab)将返回tab的对角线元素.

and some function, function(ri, ci, tab), would return the diagonal elements of tab.

如果tabdata.frame,我会做下面的事情,

If tab were a data.frame, I would do what's below,

as.data.frame(tab)[cbind(ri, ci)]

但是,我想避免使用data.frame语法.我还想避免for循环,因为这往往很慢.

but, I would like to avoid data.frame syntax. I would also like to avoid a for loop, as this tends to be slow.

推荐答案

有一种比强制转换为矩阵或data.frame更快的方法.只需使用[data.frame函数.

There is a faster way to do this than coercing to either matrix or data.frame. Just use the [data.frame function.

`[.data.frame`( tab,  cbind(ri,ci) )
[1]    NA 42190    NA

这是[.data.frame函数的功能语法.

这篇关于取得具有(row,col)索引序列的data.table slice的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆