S.Pirtti
S.Pirtti

Reputation: 35

Combining functions in R

I'm doing a task but I have no idea how to combine 2 functions so that I get multiple answers from one. I'm doing t.testing and had to write out the function, and then i had to write an if-else loop that states wether the hypotesis will be rejected or not. Both of them work individually but I can't figure out how to merge them so when I run the code I get a numerical answer and a line stating whether the hypotesis will be rejected. For the numerical answer I've got this:

osuustesti <- function(x1,x2,n1,n2) {
    ((x1/n1)-(x2/n2))/sqrt((1/n1 + 1/n2)*((x1+x2)/(n1+n2))*(1-((x1+x2)/(n1+n2))))
}

And for the line stating what will be done with the hypotesis I've got this:

osuustesti2 <- function(x1,x2,n1,n2,alpha) {
    if(abs(((x1/n1)-(x2/n2))/sqrt((1/n1 + 1/n2)*((x1+x2)/(n1+n2))*(1-((x1+x2)/(n1+n2)))))> qnorm(alpha/2,lower.tail=FALSE)) {
        cat("Nollahypoteesi hylätään")} else{cat("Nollahypoteesi hyväksytään")
    }
}

I have no idea how to combine them into 1 so when I run the code I get both the numerical value and the line... I tried to copying both functions and adding them with & but that didn't work at all...

Upvotes: 1

Views: 1316

Answers (1)

pogibas
pogibas

Reputation: 28339

Something like this should work:

osuustesti <- function(x1, x2, n1, n2, alpha = 0.05) {
    numer <- x1 / n1 - x2 / n2 
    denum <- sqrt((1 / n1 + 1 / n2) * 
                  ((x1 + x2) / ( n1 + n2)) * 
                  (1 - ( x1 + x2) / (n1 + n2)))
    result <- numer / denum

    if (result > qnorm(alpha / 2, lower.tail = FALSE)) {
        cat("Nollahypoteesi hylätään\n")
    } else {
        cat("Nollahypoteesi hyväksytään\n")
    }
    return(result)
}

I save result to result object, then compare it to alpha, cat the string and in the end use return() to return result from the function.

Upvotes: 1

Related Questions