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

1
  • 1
    Without a 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. Commented Jan 21, 2015 at 20:05

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

@MrFlick Agreed. I added a comment.
Thanks guys...as simple as that ?!! (Mr. Flick, I think you actually helped me answer another question as well).
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))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.