Loop through data frame and variable names

后端 未结 5 924
终归单人心
终归单人心 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:23

    To further add to Beasterfield's answer, it seems like you want to do some number of complex operations on each of the data frames.

    It is possible to have complex functions within an apply statement. So where you now have:

    for (i in dflist) {
      # Do some complex things
    }
    

    This can be translated to:

    lapply(dflist, function(df) {
      # Do some complex operations on each data frame, df
      # More steps
    
      # Make sure the last thing is NULL. The last statement within the function will be
      # returned to lapply, which will try to combine these as a list across all data frames.
      # You don't actually care about this, you just want to run the function.
      NULL
    })
    

    A more concrete example using plot:

    # Assuming we have a data frame with our points on the x, and y axes,
    lapply(dflist, function(df) {
      x2 <- df$x^2
      log_y <- log(df$y)
      plot(x,y)
      NULL
    })
    

    You can also write complex functions which take multiple arguments:

    lapply(dflist, function(df, arg1, arg2) {
      # Do something on each data.frame, df
      # arg1 == 1, arg2 == 2 (see next line)
    }, 1, 2) # extra arguments are passed in here
    

    Hope this helps you out!

提交回复
热议问题