Loop through data frame and variable names

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

    Using the example of @Roland, I wanted to show you the ggplot2 equivalent. First we have to change the datset a bit:

    First the original data:

    > dflist
    [[1]]
               x           y
    1  0.9148060 -0.10612452
    2  0.9370754  1.51152200
    3  0.2861395 -0.09465904
    4  0.8304476  2.01842371
    5  0.6417455 -0.06271410
    6  0.5190959  1.30486965
    7  0.7365883  2.28664539
    8  0.1346666 -1.38886070
    9  0.6569923 -0.27878877
    10 0.7050648 -0.13332134
    
    [[2]]
                x          y
    1   0.6359504 0.33342721
    2  -0.2842529 0.34674825
    3  -2.6564554 0.39848541
    4  -2.4404669 0.78469278
    5   1.3201133 0.03893649
    6  -0.3066386 0.74879539
    7  -1.7813084 0.67727683
    8  -0.1719174 0.17126433
    9   1.2146747 0.26108796
    10  1.8951935 0.51441293
    

    and put the data into one data.frame, with an id column

    require(reshape2)
    one_df = melt(dflist, id.vars = c("x","y"))
    > one_df
                x           y L1
    1   0.9148060 -0.10612452  1
    2   0.9370754  1.51152200  1
    3   0.2861395 -0.09465904  1
    4   0.8304476  2.01842371  1
    5   0.6417455 -0.06271410  1
    6   0.5190959  1.30486965  1
    7   0.7365883  2.28664539  1
    8   0.1346666 -1.38886070  1
    9   0.6569923 -0.27878877  1
    10  0.7050648 -0.13332134  1
    11  0.6359504  0.33342721  2
    12 -0.2842529  0.34674825  2
    13 -2.6564554  0.39848541  2
    14 -2.4404669  0.78469278  2
    15  1.3201133  0.03893649  2
    16 -0.3066386  0.74879539  2
    17 -1.7813084  0.67727683  2
    18 -0.1719174  0.17126433  2
    19  1.2146747  0.26108796  2
    20  1.8951935  0.51441293  2
    

    and make the plot:

    require(ggplot2)
    ggplot(one_df, aes(x = x, y = y)) + geom_point() + facet_wrap(~ L1)
    

    enter image description here

提交回复
热议问题