Greetings,

I am getting errors with the following code because the software does not recognize a change in shapiro.test(x)$data.name in line 3 of the function SWtest.

SWtest <- function(x) {
cat("S-W statistic for",
shapiro.test(x)$data.name,"is",
round(shapiro.test(x)$statistic,4),
"with p-value =",
round(shapiro.test(x)$p.value,4),"\n")
}

How am I to extract the data.name variable in this situation so the sentence output
reflects the correct variable? x should be changing.

Source:

seed <- 1234
x1 <-rnorm(10, mean = 5, sd = 3)
x2 <- runif(10, min = 2, max = 4)
shapiro.test(x1)
shapiro.test(x2)

SWtest <- function(x) {
cat("S-W statistic for",
shapiro.test(x)$data.name,"is",
round(shapiro.test(x)$statistic,4),
"with p-value =",
round(shapiro.test(x)$p.value,4),"\n")
}
SWtest(x1)
SWtest(x2)

Output:
SWtest(x1)
S-W statistic for x is 0.9475 with p-value = 0.6388
SWtest(x2)
S-W statistic for x is 0.9403 with p-value = 0.5562

Thank you.
Sincerely,
Mary A. Marion

Hi. Normally, I'd urge the `reprex`

described in the FAQ: What's a reproducible example (`reprex`) and how do I do one? Using a reprex, complete with representative data will attract quicker and more answers.

This code is simple enough not to need one though.

```
seed <- 1234
x1 <-rnorm(10, mean = 5, sd = 3)
x2 <- runif(10, min = 2, max = 4)
shapiro.test(x1)
#>
#> Shapiro-Wilk normality test
#>
#> data: x1
#> W = 0.73903, p-value = 0.002624
shapiro.test(x2)
#>
#> Shapiro-Wilk normality test
#>
#> data: x2
#> W = 0.93302, p-value = 0.4782
SWtest <- function(x) {
cat("S-W statistic for",
shapiro.test(x)$data.name,"is",
round(shapiro.test(x)$statistic,4),
"with p-value =",
round(shapiro.test(x)$p.value,4),"\n")
}
outcome <- SWtest(x1)
#> S-W statistic for x is 0.739 with p-value = 0.0026
outcome
#> NULL
plain <- shapiro.test(x1)
plain
#>
#> Shapiro-Wilk normality test
#>
#> data: x1
#> W = 0.73903, p-value = 0.002624
str(plain)
#> List of 4
#> $ statistic: Named num 0.739
#> ..- attr(*, "names")= chr "W"
#> $ p.value : num 0.00262
#> $ method : chr "Shapiro-Wilk normality test"
#> $ data.name: chr "x1"
#> - attr(*, "class")= chr "htest"
```

^{Created on 2020-04-04 by the reprex package (v0.3.0)}

Illustrates the issue. `SWtest`

only sends its output to `stdout`

. It can't be assigned to an object, as written.

`shapiro.test(),`

on the other hand, can be easily captured.

The implications for rewriting `shapiro.test`

should be pretty clear--building it up from plain[1:4] with `paste`

as one option.

If you get stuck, of course, please come on back.

system
Closed
April 26, 2020, 1:58am
3
This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.