Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

r - Error Shapiro-Wilk Test for multiple columns

I have a dataframe and trying to execute a shapiro-wilk test in multiples columns.

When a try to use the following code:

DF.Shapiro <- do.call(rbind, lapply(DF[c(3:41)], function(x) shapiro.test(x)[c("statistic", "p.value")])) Always appears this message:

"Error in shapiro.test(x) : all 'x' values are identical"

Or

"Error in FUN(X[[i]], ...) : all 'x' values are identical"

How can a solve this?

question from:https://stackoverflow.com/questions/65601216/error-shapiro-wilk-test-for-multiple-columns

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

1 Answer

0 votes
by (71.8m points)

Without data it's difficult to say but maybe the following untested solution will do what the question asks for.

num <- which(sapply(DF[3:41], is.numeric))
num <- intersect(3:41, num)

do.call(
  rbind.data.frame,
  lapply(DF[num], function(x){
    tryCatch(shapiro.test(x)[c("statistic", "p.value")],
             error = function(e) e)
  })
)

Edit

If some of the tests return an error, the lapply instruction will return different types of data and the rbind.data.frame method will also give an error. The following code solves that problem by saving the lapply results in a named list, test_list and checking the list members for errors before binding the right ones.

test_list <- lapply(DF[num], function(x){
  tryCatch(shapiro.test(x)[c("statistic", "p.value")],
           error = function(e) e)
})

err <- sapply(test_list, inherits, "error")
err_list <- test_list[err]
do.call(rbind.data.frame, test_list[!err])

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...