Julia L
Julia L

Reputation: 27

How do I create a function to run a t.test over multiple columns

I am trying to run a t.test with a binomial variable and outcome variable like this

t.test(outcomevar~binomialvar, data=d)

But I want to write a function to run this for 5 columns (column 22 to 27) so I dont have to continue to write out the full code.

Im new to writing functions so im just a little confused on the syntax, this is what I tried

fun1<- function(x){t.test(c(22:27)==x ,binomialvar, data)%>%pvalue()

Upvotes: 1

Views: 48

Answers (1)

akrun
akrun

Reputation: 886938

We can just loop over the names, create a formula with reformulate

out <- sapply(names(d)[22:27), function(nm)
       t.test(reformulate("binomialvar", response = nm), data = d)$p.value)

Upvotes: 2

Related Questions