Why my for loop fails?

for (x in c("JP_Employment", "JP_MainJobHours","JP_FullPartTime","JP_JobPay","JP_MainJobEarn")) {
  t.test(table2.11$x, CG_Interview_Pre_1$x, alternative = "two.sided")

I need to test these 5 variables. So 5 times together. I tried to do a for loop. But it failed. Can anyone help me?

The $x syntax is not going to use the x that is in the for loop scope, but rather will expect to find exactly an x variable in the table to the left of the $ symbol. If you want to use 'x' programatically and evaluate it use the double square brackets operation like in this example. I also show how you can iterate with purrr map rather than for loops.


#example data
(table1 <- filter(iris,Species=="setosa") %>% select(-Species))
(table2 <- filter(iris,Species=="virginica"%>% select(-Species))

(nameset <- names(table1))
for (x in nameset) {
         alternative = "two.sided") %>%
  #better ?
 (myresults <-  map(nameset,
      ~ t.test(table1[[.x]],
               alternative = "two.sided")) %>% set_names(nameset))
1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.