Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in R Programming by (50.2k points)

Whenever I am writing the reshape(), it is throwing the following specific error: failed to guess time-varying variables from their names.

How can I catch this specific error from reshaping and make: if(that specific error came up) return(NA)?

Say for instance:

input <- data.frame(id = 1:3, school = LETTERS[1:3], read_2018 =20:22, read_2019 = 30:32)

out <- reshape(input, dir = 'long', idvar = c("id", "school"), varying = c('read_2018', 'read_2019'))

# if(`out` gives that specific error) return(NA)

1 Answer

0 votes
by (107k points)

You can simply use the tryCatch that will help you to capture the error message and return NA if that specific error message occurs.

out <- tryCatch({reshape(input, dir = 'long', idvar = c("id", "school"), 

                 varying = c('read_2018', 'read_2019'))}, 

     error = function(e) {

       if(as.character(e) == "Error in guess(varying): failed to guess time-varying variables from their names\n") NA 

       else e

})

out

#[1] NA

If you are a beginner and want to know more about R then do check out the R programming tutorial

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...