0

This is very strange. When I try to select columns on my data.table by doing

df1[, 30]

It just gives me 30, or whatever number I put in there. Not column 30.

Data here: https://github.com/pourque/country-data/blob/master/data/df1.csv

I've checked, and everything works properly when I just produce a test data.frame:

df2 <- data.frame(x = 1:3, y = 3:1, z = 7:9)
> df2[, 2]
[1] 3 2 1

Any ideas on what might be happening?

5
  • 3
    data frame or a data table? the behavior you described looks like a data table one. Commented May 4, 2015 at 18:53
  • My bad, it is a data table. I'll convert it into a data frame and hopefully that will fix this! Commented May 4, 2015 at 18:55
  • 2
    Just ignore my comment. I thought you want it as a column. If it is a data.table, df2[,2, with=FALSE] Commented May 4, 2015 at 18:55
  • 6
    For reference, it's the first question in the faq :) github.com/Rdatatable/data.table/wiki/vignettes/… You may want to edit the question title (since it says "data frame") Commented May 4, 2015 at 18:56
  • Oh...well this is embarrassing. Thank you! :D Commented May 4, 2015 at 18:59

1 Answer 1

8

When working with data.table you need to use following to chose column by numbers:

df2[, 2]
df2[, .SD, .SDcols=2]

This will still return data.table, not a vector.
As always on list you can also use below to return a vector:

df2[[2]]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.