如何通过R中的索引从数据表中提取列?(How to extract columns from data table by indices in R?)

编程入门 行业动态 更新时间:2024-10-27 18:29:12
如何通过R中的索引从数据表中提取列?(How to extract columns from data table by indices in R?)

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

以下方法有效:

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

但以下不是:

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

事实上,第二种方法给了我一个结果:

4 5 6

有人能告诉我为什么会这样吗? 这两种方法看起来与我相同。

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

the following method works:

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

but the following doesn't:

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'之前使用双点( .. )来提取列

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)

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

Or another option is with = FALSE

dt[, a, with = FALSE]

data

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

更多推荐

本文发布于:2023-08-05 04:56:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1428489.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数据表   索引   extract   columns   table

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!