Angus
Angus

Reputation: 355

Confused by Error: object 'carryover' not found

I want to sample a large data set of 100,000 rows and do a calculation with each of 10,000 random values chosen. The sampling chooses a random value called "unused", and based on the value chosen there are three choices using if statements, but for some reason the variable "carryover" is not found.

Code is:

options(width=10000)
unused <- round(runif(100000, 0, 600),0)

B <-10000
unused <-matrix(sample(unused,size=B,replace=TRUE),nrow=B)
for (i in 1:B){
  if (unused[i]==0){
    deduct[i] <- 0
    carryover[i] <- 0
    used[i] <- 0
    if (unused[i] > 200)
      deduct[i] <- unused[i]-200
    carryover[i] <- 200
    used[i] <- carryover[i]+400
    if (unused[i] >0 & unused[i] <= 200)
      deduct[i] <- 0
    carryover[i] <- unused[i]
    used[i] <- carryover[i]+400
  }
}
View(data.frame(unused,deduct,carryover,used))

Upvotes: 0

Views: 40

Answers (1)

Jim Kloet
Jim Kloet

Reputation: 440

Looks like you're missing a few closing curly brackets for your if conditions. The following runs for me and doesn't generate missing variable errors or mismatched row errors:

options(width=10000)
unused <- round(runif(100000, 0, 600),0)

B <-10000
unused <-matrix(sample(unused,size=B,replace=TRUE),nrow=B)
deduct <- NULL
used <- NULL
carryover <- NULL

for (i in 1:B) {
  if (unused[i]==0) {
    deduct[i] <- 0
    carryover[i] <- 0
    used[i] <- 0
  }

  if (unused[i] > 200) {
      deduct[i] <- unused[i]-200
      carryover[i] <- 200
      used[i] <- carryover[i]+400
  }

if (unused[i] >0 & unused[i] <= 200) {
      deduct[i] <- 0
    carryover[i] <- unused[i]
    used[i] <- carryover[i]+400
  }
}

View(data.frame(unused,deduct,carryover,used))

Upvotes: 2

Related Questions