0

I'm fairly new to R programming. Can someone say why this code keeps giving an error : paste0("emissions_for_",yr) <- sum(nei_tst[,var][select_obs], na.rm=TRUE)

  • (nei_tst is a dataframe)
  • (var is a variable that was assigned the name of one column in that dataframe)
  • select_obs is a variable with logical elements (result of test : yr == "1999")

I get the foll. error : Error in paste0("emissions_for_", yr) <- sum(nei_tst[, var][select_obs], : target of assignment expands to non-language object

Robert
  • 37
  • 3
  • 1
    Without a [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example), it's not easy to provide you with specifics. I think you want something like `tapply(nei_tst[,var], nei_tst$yr, sum, na.rm=TRUE)` will give you the result you want. Building variable names like they are strings is just not a good idea in R and often makes things much more difficult to work with. I strongly suggest you avoid this strategy. – MrFlick Jan 21 '15 at 20:05

2 Answers2

1

You have to use assign if the name of the object is stored as a character string:

assign(paste0("emissions_for_",yr), sum(nei_tst[,var][select_obs], na.rm=TRUE))

However, creating multiple variables dynamically to store multiple values in not good R style. You should store all related values in a single object, e.g., a list or a data frame.

Sven Hohenstein
  • 80,497
  • 17
  • 145
  • 168
0

Might you not be better off to create a dataframe, and index by year?

emissions <- data.frame(yr, sum(nei_tst[,var][select_obs], na.rm=TRUE))
Scott C Wilson
  • 19,102
  • 10
  • 61
  • 83