2
I have this df
:
df_1 <- data.frame(
x = replicate(
n = 6, expr = runif(n = 30, min = 20, max = 100), simplify = TRUE
),
y = as.factor(sample(x = 1:3, size = 30, replace = TRUE))
)
I would like to know the cause of the first two functions functioning and the third and fourth not. I chose the function pairwise.t.test
arbitrarily to illustrate.
For me, they would all be equivalent:
1)
vars <- names(df_1)[c(1:6)]
for (i in vars) {
print(
pairwise.t.test(x = df_1[, i], df_1$y, p.adj = 'bonferroni')
)
}
Works.
2)
for (i in names(df_1)[c(1:6)]) {
print(
pairwise.t.test(x = df_1[, i], df_1$y, p.adj = 'bonferroni')
)
}
Also works.
The following loop, which for me is equivalent to the previous ones, is not executed:
3)
for (i in df_1) {
print(
pairwise.t.test(x = names(i)[c(1:6)], i$y, p.adj = 'bonferroni')
)
}
4)
Finally, we know that:
df_1[1]
amounts to
df_1[, 1]
and
df_1[,1]
All return to the first column of df
. But if I remove the comma (,
) of df_1[, i]
or withdraw the space between ,
and i
([,i]
) in function 1) and 2) the loop does not work and "works wrong" respectively:
comma-free
for (i in vars) {
print(
pairwise.t.test(x = df_1[i], df_1$y, p.adj = 'bonferroni')
)
}
Error in tapply(x, g, Mean, na.rm = TRUE) : Arguments must have same length
without the space
for (i in vars) {
print(
pairwise.t.test(x = df_1[,i], df_1$y, p.adj = 'bonferroni')
)
}
# Pairwise comparisons using t tests with pooled SD
# data: df_1[, i] and df_1$y
# 1 2
# 2 1 -
# 3 1 1
# P value adjustment method: bonferroni
- What are the reasons for 3) and 4) do not work?
Tomás, thanks. Just one additional question: how would this loop look in a list? Example list:
lista <- split(df_1, df_1$y)
– neves
I don’t know if I understand correctly. Is it worth asking a new question explaining better?
– Tomás Barcellos