通过数字索引选择 data.table 中的多个列 [英] Select multiple columns in data.table by their numeric indices
本文介绍了通过数字索引选择 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 的版本 <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屋!
查看全文