2

I am trying to construct a script in r to force it to ignore objects it can’t find.

A simplified version of my script is as follows

Trial<-sum(a,b,c,d,e)

A-e are numeric vectors generates by calculating the sum of a column in a data frame.

My problem is I want to use the same script over multiple different conditions (and have far more objects than just a-e). For some of these conditions some of the objects a-e may not exist. Therefore r returns error object d not found.

To avoid having to generate a unique script for each condition I would like to force to ignore any missing objects.

I would be grateful for any help!

  • 1
    It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. – MrFlick Oct 22 '18 at 20:18

1 Answers1

1

Welcome to SO! As mentioned in the comments, in the future try to include a working example in your question. The preferred solution to your problem would be to avoid assigning values to individual variables in the first place. Try to restructure your code so that your column sums get assign to, for example, a list. In the example below, I create some sample data, assign column sum values to a vector, and compute the sum of the vector, without creating a new variable for each column.

# Create sample data
rData <- as.data.frame(matrix(c(1:6), nrow=6, ncol=5, byrow = TRUE))
print(rData)

# Compute column sum
sumVec <- apply(rData, 2, sum)
print(sumVec)

# Compute sum of column sums
total <- sum(sumVec)
print(total)

If you have to use individual variables, before adding them up, you could check if the variable exists, and if not, create it and assign NA. You can then compute the sum of your variables after excluding NA.

# Sample variables
a <- 15
b <- 20
c <- 50

# Assign NA if it doesn't exist (one variable at a time)
if(!exists("d")) { d <- NA }

# Assign NA using sapply (preferred)
sapply(c("a","b","c","d","e"), function(x) 
  if(!exists(x)) { assign(x, NA, envir=.GlobalEnv) } 
)

# Compute sum after excluding NA
altTotal <- sum(na.omit(c(a,b,c,d,e)))
print(altTotal)

Hopefully this will get you closer to the solution!

MatAff
  • 1,250
  • 14
  • 26