starbuckslychee
starbuckslychee

Reputation: 1

Using the merge function in R for multiple values

I have calculated multiple values of RMSE for my data, and would like to put it into one table using the merge function in R. Here is the code that I currently have:

merge(merge(merge(merge(merge(merge(merge(merge(merge(merge(merge(merge(RMSE_G_te, RMSE_GS_p, by = "name"), 
                                                                                RMSE_GS_sistar, by = "name"), 
                                                                          RMSE_GS_nistar, by = "name"), 
                                                                    RMSE_GS_s, by = "name"), 
                                                              RMSE_GS_t, by = "name"),
                                                        RMSE_GS_d, by = "name"), 
                                            RMSE_GI_p, by = "name"), 
                                      RMSE_GI_sistar, by = "name"), 
                                RMSE_GI_nistar, by = "name"), 
                          RMSE_GI_s, by = "name"), 
                    RMSE_GI_t, by = "name"), 
              RMSE_GI_d, by = "name") 

The RMSE values were calculated using the rmse() function from the Metrics package.

Is there a way I can clean this up with a for loop? Any help is appreciated, thank you!

Edit: I tried to put the values in a list and got the following error:

df <- as.list(RMSE_G_te, RMSE_GS_p, RMSE_GS_sistar, RMSE_GS_nistar, RMSE_GS_s, RMSE_GS_t, RMSE_GS_d, RMSE_GI_p, RMSE_GI_sistar, RMSE_GI_nistar, RMSE_GI_s, RMSE_GI_t, RMSE_GI_d)
reduce(df, merge, by = "name")

Error in fix.by(by.x, x) : 'by' must specify a uniquely valid column

Upvotes: 0

Views: 137

Answers (1)

GuedesBF
GuedesBF

Reputation: 9878

You should first put all your data.frames in a list:

lst<-mget(ls(pattern='RMSE_G'))

then call base R Reduce() or purrr:reduce():

library(purrr)
reduce(lst, ~merge(.x, .y, by='name'))

Upvotes: 1

Related Questions