0

I have successfully created a dynamic variable inside a for loop. I want to perform a simple one sample ttest on the created variable. How do I do that within the loop/ dynamically? This is what I have written -

for (i in 1:15) {
  
  # create a dynamic variable name
  df_nam <- paste("df", i, sep = "_")
  
  # give it values
  assign(df_nam, df[df$k == i, ])
  
  # create variable that would hold the results of ttest
  ttest_nam <- paste("ttest_k", i, sep = "_")

  # what do I put here??
  assign(ttest_nam, as.formula(paste("t.test(", df_nam$result, ")")))
}

The way it currently is, given me this error - Error in class(ff) <- "formula" : attempt to set an attribute on NULL. Is there a way to even do this, or will I have to perform the ttest individually?

I worry that when the length is large (more than 15 as it currently is), writing each set of tests down would be inviting errors.

Nilima
  • 197
  • 1
  • 2
  • 9
  • 2
    Don't assign a formula to the new variable, assign the value you want there, e.g. `t.test(df[df$k == i, ])`. But the whole idea of creating 30 separate variables for this instead of a single list variable is bad. – user2554330 Aug 03 '22 at 00:46
  • 1
    Per the above, you really don't want to do this as it will create all sorts of headaches. If you want to have separate t-tests on many different sets of variables, look into the `dplyr` package, where you can use `summarise()` and `across()` to repeat this on different columns easily. You could also use `purrr::map` to accomplish this in a more natural way. – socialscientist Aug 03 '22 at 06:16

0 Answers0