I'm trying to repeat a complex syntax for a set of variables. Essentially, using a data set like:
df <- data.frame( X=1:10, Y=6:15, Z=11:20)
I'd like to replace syntax like:
mean(df$X)
mean(df$Y)
mean(df$Z)
with a Loop like:
for (n in c("X", "Y", "Z")) {mean(df$n)}
However, this rather Stata-like programming does not work in R. It seems like the loop writes df$"X" instead of df$X. Is there a simple work around?
UPDATE: Instead of computing the mean I have a more complex function where I repeatedly need to access variable names. My question is therefor not about computing means but using the loop function.
sapply(df,mean)?