1

I am new to R and have am having trouble understanding how to substitute a variable name for column name. For example, the code below works fine finding the row with the max value for col2 with defined column names

> df<-data.frame(name=sample(LETTERS[1:5]),val1=sample(5), val2=sample(5))
> df
  name val1 val2
1    B    3    1
2    C    4    3
3    E    5    2
4    D    2    4
5    A    1    5
> df[which(df$val2 == max(df$val2)),]
5    A    1    5

But if I cannot seem to get this work with a string variable for the column name such as

colName = "val2"
JerryKur
  • 7,279
  • 6
  • 24
  • 33
  • `df[which(df[,colName]==max(df[,colName])),]` – akrun Jan 18 '15 at 17:08
  • See also [here](http://stackoverflow.com/questions/18222286/select-a-data-frame-column-using-and-the-name-of-the-column-in-a-variable/) – David Arenburg Jan 18 '15 at 17:13
  • "$ is a shorthand operator, where `x$y` is equivalent to `x[["y", exact = FALSE]]`" http://adv-r.had.co.nz/Subsetting.html. You see for instance `mtcars$cy` is same as `mtcars$cyl` – Khashaa Jan 18 '15 at 17:15
  • Thanks guys for the pointers. I have some much to learn about R. – JerryKur Jan 18 '15 at 18:49

0 Answers0