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?


source to share

2 answers

Please refer to the data section 1.1 of the .table FAQ:

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]




Your syntax should work for data frames. data.table

has its own unique rules.

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

[1] 1 2 3
[1] 1 2 3
[1] 1 2 3
[1] 1 2 3




All Articles