0

If I run a sum function and explicitly call the named column I have no problem. But if I try to build the reference out of a passed character vector I get this error.

All the answers to this error I can find talk about characters in the column itself, which is not my problem. It runs fine if I type it out. I think if has something to do with $.

Thanks in advance.

pollut<-"nitrate"

> sum(test1$nitrate, na.rm=TRUE)

[1] 67.089

> sum(paste("test1$",pollut,sep=""), na.rm=TRUE)

Error in sum(paste("test1$", pollut, sep = ""), na.rm = TRUE) : invalid 'type' (character) of argument

Edit...A suggested answer did identify the problem but not the solution as Richard so clearly did.

Werner Hertzog
  • 2,002
  • 3
  • 24
  • 36
  • 1
    What makes you think that `test1$nitrate` is the same as `"test1$nitrate"`? They are absolutely not the same, as you have discovered. I think you want `sum(test1[[pollut]], na.rm=TRUE)` – Rich Scriven Jan 30 '16 at 23:51
  • 2
    You can't use the `$` operator with variables. See http://stackoverflow.com/questions/18222286/select-a-data-frame-column-using-and-the-name-of-the-column-in-a-variable/ and http://stackoverflow.com/questions/34544888/dollar-operator-as-function-argument-for-sapply-not-working-as-expected/ – NGaffney Jan 31 '16 at 00:29
  • Richard, thank you that worked. I would agree they aren't the same but as I'm just learning I was not aware that it evaluated differently as I'd used that structure elsewhere and it worked. – Sherman sims Jan 31 '16 at 02:33
  • NGaffney thanks. I'd assumed that was the case. – Sherman sims Jan 31 '16 at 02:40

0 Answers0