通过其数字索引选择data.table中的多个列 [英] Select multiple columns in data.table by their numeric indices

查看:71
本文介绍了通过其数字索引选择data.table中的多个列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 data.table 中使用其数字索引(位置)的向量选择多列?

How can we select multiple columns using a vector of their numeric indices (position) in data.table?

这就是我们对 data.frame 的处理方式:

This is how we would do with a data.frame:

df <- data.frame(a = 1, b = 2, c = 3)
df[ , 2:3]
#   b c
# 1 2 3


推荐答案

对于 data.table版本 > = 1.9.8 ,以下所有方法都可以正常工作:

For versions of data.table >= 1.9.8, the following all just work:

library(data.table)
dt <- data.table(a = 1, b = 2, c = 3)

# select single column by index
dt[, 2]
#    b
# 1: 2

# select multiple columns by index
dt[, 2:3]
#    b c
# 1: 2 3

# select single column by name
dt[, "a"]
#    a
# 1: 1

# select multiple columns by name
dt[, c("a", "b")]
#    a b
# 1: 1 2






对于 data.table 版本和lt; 1.9.8 (要选择数字列,必须使用 with = FALSE ),请参见此答案的先前版本。另请参阅v1.9.8上的新闻,可能会更改,第3点。


For versions of data.table < 1.9.8 (for which numerical column selection required the use of with = FALSE), see this previous version of this answer. See also NEWS on v1.9.8, POTENTIALLY BREAKING CHANGES, point 3.

这篇关于通过其数字索引选择data.table中的多个列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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