I am looking for a way to automate some diagrams in R using a FOR loop:
dflist <- c(\"dataframe1\", \"dataframe2\", \"dataframe3\", \"dataframe4\")
for (i in
Concerning your actual question you should learn how to access cells, rows and columns of data.frame
s, matrix
s or list
s. From your code I guess you want to access the j
'th columns of the data.frame i
, so it should read:
mean( i[,j] )
# or
mean( i[[ j ]] )
The $
operator can be only used if you want to access a particular variable in your data.frame, e.g. i$var1
. Additionally, it is less performant than accessing by [, ]
or [[]]
.
However, although it's not wrong, usage of for
loops it is not very R'ish. You should read about vectorized functions and the apply
family. So your code could be easily rewritten as:
set.seed(42)
dflist <- vector( "list", 5 )
for( i in 1:5 ){
dflist[[i]] <- data.frame( A = rnorm(100), B = rnorm(100), C = rnorm(100) )
}
varlist <- c("A", "B")
lapply( dflist, function(x){ colMeans(x[varlist]) } )