Reputation: 45
I am subsetting a set of data frames, each data frame will be subsetted into several smaller data frames. Some will produce empty data frames and give an error as in title.
My question: if I ran the script in R console, the script will be executed and new data frames will be generated even with the error messages. but if I use "source" in R studio or try to put the scripts in a function or use a for loop, the scripts will stop running and just display the error message.
Is there a solution? thank you!
Upvotes: 0
Views: 34171
Reputation: 544
I ran across this error using the likert package with grouping. See here:
plot(likert(KnowledgeAndInterest[,c(1:2)], grouping = KnowledgeAndInterest[,3]), legend.position="right") +
scale_fill_manual(values = brewer.pal(n=5,"RdYlBu"), breaks = c("None at all", "A little", "A moderate amount", "A lot", "A very lot")) +
guides(fill = guide_legend(title=""))
KnowledgeAndInterest is a dataframe containing only 3 columns of my data, created especially for the likert. It took me a while to figure out that the error was due to incomplete data (NA values) in column 3, my grouping column. Reducing the data frame to only use complete cases before calling likert fixed the problem:
KnowledgeAndInterest <- KnowledgeAndInterest[complete.cases(KnowledgeAndInterest), ]
I hope this is of assistance to anyone with a similar issue.
Upvotes: 0
Reputation: 3914
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
Upvotes: 3