You are not sub-setting your data frame correctly and I would recommend to fix sub-setting instead of trying to ignore the error
Here is one example how wrong approach to create a new column can lead to the error you are getting:
df <- data.frame(a = -(1:5), b = 1:5)
df$c[which(df$a>0)] <- 7
#Error in `$<-.data.frame`(`*tmp*`, "c", value = numeric(0)) :
# replacement has 0 rows, data has 5
Instead the second statement should be:
rm(df)
df <- data.frame(a = -(1:5), b = 1:5)
df$c[df$a>0] <- 7
df
# a b c
# 1 -1 1 NA
# 2 -2 2 NA
# 3 -3 3 NA
# 4 -4 4 NA
# 5 -5 5 NA
To answer your question about catching the error in a script in general, R has try/catch set of functions:
rm(df)
df <- data.frame(a = -(1:5), b = 1:5)
tryCatch({
df <- data.frame(a = -(1:5), b = 1:5)
df$c[which(df$a>0)] <- 7
}, error = function(e)print(e) , warning = function(w) )
You can get more examples of how this function can be used in R documentation
and in the Advanced R online book by Hadley Wickham: http://adv-r.had.co.nz/Exceptions-Debugging.html