通过存储在向量中的数字索引从数据表中提取列 [英] Extract columns from data table by numeric indices stored in a vector

查看:49
本文介绍了通过存储在向量中的数字索引从数据表中提取列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从名为dt的数据表中提取第4、5和6列

I want to extract the 4th, 5th, and 6th column from a data table named dt

以下方法有效:

    dt[, c(4,5,6)]

但以下内容不是:

    a = c(4,5,6)
    dt[, a]

实际上,第二种方法给我带来了以下结果:

In fact, the second method gives me a reult of:

    4 5 6

有人可以告诉我为什么会这样吗?这两种方法看起来和我一样.

Can someone tell me why this is happening? The two method looks equivalent to me.

推荐答案

我们可以在对象'a'之前使用双点( .. )提取列

We can use double dots (..) before the object 'a' to extract the columns

dt[, ..a]
#   col4 col5 col6
#1:    4    5    6
#2:    5    6    7
#3:    6    7    8
#4:    7    8    9

或者另一个选择是 with = FALSE

dt[, a, with = FALSE]

数据

dt <- data.table(col1 = 1:4, col2 = 2:5, col3 = 3:6, col4 = 4:7, col5 = 5:8, col6 = 6:9)

这篇关于通过存储在向量中的数字索引从数据表中提取列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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