Hi Chenguang Du,
This is really a better question for R-help as R-Sig-Teaching is about
teaching statistics with R. But …
This function:
mystats <- function(x, na.omit=FALSE){
if (na.omit)
x <- x[!is.na(x)]
m <- mean(x)
n <- length(x)
s <- sd(x)
skew <- sum((x-m)^3/s^3)/n
kurt <- sum((x-m)^4/s^4)/n - 3
return(c(n=n, mean=m, stdev=s, skew=skew, kurtosis=kurt))
}
is equivalent to:
mystats <- function(x, na.omit=FALSE){if (na.omit){
x <- x[!is.na(x)]
}
m <- mean(x)
n <- length(x)
s <- sd(x)
skew <- sum((x-m)^3/s^3)/n
kurt <- sum((x-m)^4/s^4)/n - 3
return(c(n=n, mean=m, stdev=s, skew=skew, kurtosis=kurt))
}
So, the authors of that function wanted that if() statement to apply only
to the line immediately below it (i.e., this code x <- x[!is.na(x)]) and
not the rest of the function.
On Fri, Jun 14, 2019 at 1:19 PM Chenguang Du <[email protected]> wrote:
> I am reading the book R in action, but get confused by the following code
>
> mystats <- function(x, na.omit=FALSE){
>
> if (na.omit)
>
> x <- x[!is.na(x)]
>
> m <- mean(x)
>
> n <- length(x)
>
> s <- sd(x)
>
> skew <- sum((x-m)^3/s^3)/n
>
> kurt <- sum((x-m)^4/s^4)/n - 3
>
> return(c(n=n, mean=m, stdev=s, skew=skew, kurtosis=kurt))
>
> }
>
> my question is when if control statement is used inside the function, why
> the { } after the (na.omit) is not followed??? why it still works???
> --
> Chenguang Du
> Ph.D Candidate
> Educational Research and Evaluation
> School of Education
> Virginia Tech
>
> [[alternative HTML version deleted]]
>
> _______________________________________________
> [email protected] mailing list
> https://stat.ethz.ch/mailman/listinfo/r-sig-teaching
>
[[alternative HTML version deleted]]
_______________________________________________
[email protected] mailing list
https://stat.ethz.ch/mailman/listinfo/r-sig-teaching