Loop through data frame and variable names

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

    Based on Scott Ritchi solution, this would the reproducible example, hiding also the feedback message from lapply:

    # split dataframe by condition on cars hp
    f <- function() trunc(signif(mtcars$hp, 2) / 100)
    dflist <- lapply(unique(f()), function(x) subset(mtcars, f() == x ))
    

    This splits the mtcars dataframe is subsets based on the hp variable classification (0 for hp lower than 100, 1 for those in the 100's, 2 for 200's, and so on.)

    And, plot it:

    # use invisible to prevent the feedback message from lapply
    invisible(
        lapply(dflist, function(df) {
        x2 <- df$mpg^2
        log_y <- log(df$hp)
        plot(x2, log_y)
        NULL
    }))
    

    invisible() will prevent the lapply() message:

    16 
    9 
    6 
    1 
    [[1]]
    NULL
    
    [[2]]
    NULL
    
    [[3]]
    NULL
    
    [[4]]
    NULL
    

提交回复
热议问题