在data.table条件中使用列索引 [英] Using column index in data.table condition

查看:57
本文介绍了在data.table条件中使用列索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

dt <- data.table(id=c(8,5,4,9,2,7), col1=c(2,1,2,2,3,1), col2=c(1,1,1,2,3,1))

   id col1 col2
1:  8    2    1
2:  5    1    1
3:  4    2    1
4:  9    2    2
5:  2    3    3
6:  7    1    1

我想对 dt 进行子集化,以仅获取 col1 col2 2 的行.>,使用列索引而不是名称.

I want to subset dt to get only rows that contain the value 2 in any of col1 or col2 , using column indices rather than names.

编辑:要明确,我对仅知道列索引(名称未知)的情况感兴趣.

To be clear, I'm interested in situations where only column indices are known (names are unknown).

推荐答案

您可以使用 .SD .SDcols :

dt[dt[, Reduce("|", lapply(.SD, function(x) x==2)), .SDcols=2:3]]

这篇关于在data.table条件中使用列索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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