Home > database >  Using a function using loop elements
Using a function using loop elements

Time:03-17

I want to loop through a list of elements and use them in a function. Here is a partial code, from a t-test in jamovi package.

j = c("K1", "K2")

for (i in j) {  
  temp1 <- jmv::ttestIS(
    formula = i ~ T1,
    data = data1,
    vars = i,
    students = FALSE,
    eqv = TRUE)
    
  temp1
}

I get the error that the argument i is not in the dataset. I suppose it's because the function sees i as itself and not K1. Any ideas how to access the loop elements in the function?

ps. I can provide a reproducible code if needed.

CodePudding user response:

You can use as.formula(). However, please note that you are overwriting temp1 for each iteration of j here; was that your intention?

for (i in j) {  
  formula = as.formula(paste(i,"~T1"))
  temp1 <- jmv::ttestIS(
    formula = formula,
    data = data1,
    students = FALSE,
    eqv = TRUE)
  
  temp1
}

CodePudding user response:

Instead of using

for (i in j)

use

for (in in 1:length(j))
  •  Tags:  
  • r
  • Related