Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in R Programming by (5.3k points)

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

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

1 Answer

0 votes
by

To select columns in data.table by their numeric indices, do the following:

library(data.table)

dt <- data.table(Name = c("Aira", "Ben", "Cat"), 

                       Month = c(1L, 2L, 3L), 

                       Rate1 = c(15, 2, 6),

                       Rate2 = c(17, 5, 8))

To select a single column by index:

dt[, 2] 

 Month 

1: 1 

2: 2 

3: 3

To select multiple columns by index:

dt[, 2:3] 

Month Rate1 

1: 1 15 

2: 2 2 

3: 3 6

To select a single column by name:

dt[, "Name"] 

    Name 

1: Aira 

2: Ben 

3: Cat

To select multiple columns by name:

dt[, c("Name", "Month")] 

   Name Month 

1: Aira    1  

2: Ben    2 

3: Cat   3

Related questions

Browse Categories

...