Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
349 views
in Technique[技术] by (71.8m points)

r - How to check that an input *rds file is valid?

I'm writing an R function for a package which accepts an *rds file as an input argument. The user is meant to provide an input *rds file which will be read by the function, and further worked with downstream.

I'm currently confused how to best check that the *rds file provided is (1) actually an *rds file and (2) a valid *rds file.

Note on *rds and readRDS()

For instance, let's say the user provides a file with the *rds extension but it's not valid:

$ touch foobar.rds
$ R

> foo = readRDS("foobar.rds")
Error in readRDS("foobar.rds") : error reading from connection

Yes, I could write a tryCatch() as follows to catch these errors, e.g.

readInputRdsFile = function(input_rds){
    input = tryCatch(readRDS(input_rds), 
    error = function(c) stop("The input *rds is invalid. Please fix your input file.")
    )
}
## within R
> readInputRdsFile("foobar.rds")
Error in value[[3L]](cond) : 
  The input *rds is invalid. Please fix your input file.

However, this is a very generic check. There could be many things wrong with the *rds file besides "invalid" (in this case, it's not an *rds file at all, but a text file).

Are there more standard checks to include which would more precisely detect issues with the *rds file? Any insight appreciated, thank you!

question from:https://stackoverflow.com/questions/66049477/how-to-check-that-an-input-rds-file-is-valid

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...