Extract a column from a data.table as a vector, by position

后端 未结 2 1787
情话喂你
情话喂你 2020-11-28 07:42

How do I extract a column from a data.table as a vector by its position? Below are some code snippets I have tried:

DT<-data.table(x=c(1,2),y=c(3,4),z=c(5         


        
相关标签:
2条回答
  • 2020-11-28 08:19

    DT[,get(names(DT)[colNb])]

    where colNb can be an integer (the desired column number) or a variable containing the column number.

    0 讨论(0)
  • 2020-11-28 08:24

    A data.table inherits from class data.frame. Therefore it is a list (of column vectors) internally and can be treated as such.

    is.list(DT)
    #[1] TRUE
    

    Fortunately, list subsetting, i.e. [[, is very fast and, in contrast to [, package data.table doesn't define a method for it. Thus, you can simply use [[ to extract by an index:

    DT[[2]]
    #[1] 3 4
    
    0 讨论(0)
提交回复
热议问题