Loop through data frame and variable names

后端 未结 5 879
终归单人心
终归单人心 2021-01-31 13:02

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         


        
5条回答
  •  迷失自我
    2021-01-31 13:06

    Concerning your actual question you should learn how to access cells, rows and columns of data.frames, matrixs or lists. 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]) } )
    

提交回复
热议问题