NSP
NSP

Reputation: 517

R data table issue

I'm having trouble working with a data table in R. This is probably something really simple but I can't find the solution anywhere.

Here is what I have: Let's say t is the data table

colNames <- names(t)
for (col in colNames) {
    print (t$col)
}

When I do this, it prints NULL. However, if I do it manually, it works fine -- say a column name is "sample". If I type t$"sample" into the R prompt, it works fine. What am I doing wrong here?

Upvotes: 0

Views: 230

Answers (1)

Ben Bolker
Ben Bolker

Reputation: 226182

You need t[[col]]; t$col does an odd form of evaluation.

edit: incorporating @joran's explanation:

t$col tries to find an element literally named 'col' in list t, not what you happen to have stored as a value in a variable named col.

  • $ is convenient for interactive use, because it is shorter and one can skip quotation marks (i.e. t$foo vs. t[["foo"]]. It also does partial matching, which is very convenient but can under unusual circumstances be dangerous or confusing: i.e. if a list contains an element foolicious, then t$foo will retrieve it. For this reason it is not generally recommended for programming.
  • [[ can take either a literal string ("foo") or a string stored in a variable (col), and does not do partial matching. It is generally recommended for programming (although there's no harm in using it interactively).

Upvotes: 5

Related Questions