How to exclude a row in R to access a column in a data table

Suppose I have a data.table called mysample. It has several columns, two of which are weight

and height

. I can access the weight column by typing: mysample[,weight]

But when I try to write mysample[,colnames(mysample)[1]]

, I cannot see the elements weight

. Is there something wrong with my code?

+3


source to share


2 answers


Please refer to the data section 1.1 of the .table FAQ: http://cran.r-project.org/web/packages/data.table/vignettes/datatable-faq.pdf

colnames (mysample) [1] evaluates the character vector "weight", and the second argument J in data.table is an expression that evaluates within the scope of the DT. Thus, "weight" evaluates the eigenvector "weight" and you cannot see the items in the "weight" column. For an actual subset of the "weight" column, you should try:



mysample[,colnames(mysample)[1], with = F]

      

+2


source


Your syntax should work for data frames. data.table

has its own unique rules.



df <- data.frame(a=1:3, b=4:6)
df
  a b
1 1 4
2 2 5
3 3 6

df[,"a"]
[1] 1 2 3
df$a
[1] 1 2 3
df[,1]
[1] 1 2 3
df[,colnames(df)[1]]
[1] 1 2 3

      

0


source







All Articles