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.
library(tidyverse)
#example data
(table1 <- filter(iris,Species=="setosa") %>% select(-Species))
(table2 <- filter(iris,Species=="virginica"%>% select(-Species))
(nameset <- names(table1))
for (x in nameset) {
print(x)
t.test(table1[[x]],
table2[[x]],
alternative = "two.sided") %>%
print
}
#better ?
(myresults <- map(nameset,
~ t.test(table1[[.x]],
table2[[.x]],
alternative = "two.sided")) %>% set_names(nameset))