A.Birdman
A.Birdman

Reputation: 171

r data.frame code fails to run... sometimes

I have a data analysis module that I've been using for some time. From the output of a selected model, I can use a data.frame to predict outcomes over a range of values of interest. The following line should create a data.frame. Sometimes it will run, but sometimes the column 'tod' fails to create, and trips an error.

todData <- data.frame(kpsp=rep(c(0,1,0), each=10), tlwma=rep(c(0,0,1), each=10), tod=rep(seq(-0.25,4.25, by=.5),3), tod2=tod^2, doy=36)

This results in the following return:

Error in data.frame(kpsp = rep(c(0, 1, 0), each = 10), tlwma = rep(c(0, : object 'tod' not found

I did some searching but couldn't get any returns... wasn't even sure how to properly search for such an issue. Thanks for any suggestions on how to make this run consistently.

A.Birdman

Upvotes: 1

Views: 151

Answers (2)

moodymudskipper
moodymudskipper

Reputation: 47310

I think it works only when you executed tod=rep(seq(-0.25,4.25, by=.5),3) as indivudial line somewhere before. This will work:

tod=rep(seq(-0.25,4.25, by=.5),3)
todData <- data.frame(kpsp=rep(c(0,1,0), each=10), tlwma=rep(c(0,0,1), each=10), tod=tod, tod2=tod^2, doy=36)

Or if you really want to execute this several times with one line, use this function that has a default formula for tod2 (you then won't mention tod2 in your call unless needed):

create.toData <- function(kpsp,tlwma,tod,tod2=tod^2,doy){
  data.frame(kpsp=kpsp, tlwma=tlwma, tod=tod, tod2=tod2,doy=doy)
}
todData <- create.toData(kpsp=rep(c(0,1,0), each=10), tlwma=rep(c(0,0,1), each=10), tod=rep(seq(-0.25,4.25, by=.5),3), doy=36)

Upvotes: 0

akrun
akrun

Reputation: 887088

The error happens because we are trying to create new columns based on a column that was created within the data.frame call. A variable within the data.frame can be accessed after the data.frame object is created. We can use the data.frame call to create the initial columns and then with mutate (from dplyr) or within or transform (from base R) create new columns that depend on the initial columns.

todData <- data.frame(kpsp=rep(c(0,1,0), each=10), 
      tlwma=rep(c(0,0,1), each=10), tod=rep(seq(-0.25,4.25, by=.5),3),
      doy = 36)

todData <- within(todData, {tod2 <- tod^2})   

Or

todData <- transform(todData, tod2 = tod^2)

Upvotes: 1

Related Questions