Open In App

Extract data.table Column as Vector Using Index Position in R

Improve
Improve
Like Article
Like
Save
Share
Report

The column at a specified index can be extracted using the list sub-setting, i.e. [[, operator. The double bracket operator is faster in comparison to the single bracket, and can be used to extract the element or factor level at the specified index. In case, an index more than the number of rows is specified, then an exception stating index out of bounds is returned. Single bracket [, operator cannot be used here, because it returns a subset of the data table, that is a data.table element as the output, not an atomic vector. Constant time is required to perform this operation. 

Example:

R




library("data.table")
  
# declaring data table
data_frame <- data.table(col1 = c(2,4,6), 
                         col2 = c(4,6,8), 
                         col3 = c(8,10,12), 
                         col4 = c(20,16,14))
  
print ("Original DataTable")
print (data_frame)
  
# extracting column 2
print ("Column 2 as a vector")
  
vec <-  data_frame[[2]]
print (vec)


Output

[1] “Original DataTable”

  col1 col2 col3 col4

1:    2    4    8   20

2:    4    6   10   16

3:    6    8   12   14

[1] “Column 2 as a vector”

[1] 4 6 8

Every column of the data.table can also be extracted in a separate vector, by looping over the entire data.table. ncol() method can be used to return the total number of columns in the data.table. The total time required to carry this operation is equivalent to O(n), where n are the columns. 

Example:

R




# getting required libraries
library("data.table")
  
# declaring data table
data_table <- data.table(col1 = c(2,4,6), 
                         col2 = FALSE
                         col3 = LETTERS[1:3])
  
print ("Original DataTable")
print (data_table)
  
# getting number of columns
cols <- ncol(data_table)
  
# looping through columns
for (i in 1:cols){
    
    # getting ith col
    cat(i, "th col \n")
    print(data_table[[i]])
}


Output

[1] “Original DataTable”

  col1  col2 col3

1:    2 FALSE    A

2:    4 FALSE    B

3:    6 FALSE    C

1 th col

[1] 2 4 6

2 th col

[1] FALSE FALSE FALSE

3 th col

[1] “A” “B” “C”



Last Updated : 17 May, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads