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?
You need
t[[col]];t$coldoes an odd form of evaluation.edit: incorporating @joran’s explanation:
t$coltries to find an element literally named'col'in listt, not what you happen to have stored as a value in a variable namedcol.$is convenient for interactive use, because it is shorter and one can skip quotation marks (i.e.t$foovs.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 elementfoolicious, thent$foowill 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).