Dette ville være mere generelt, forudsat at antallet af tabeller, du har med at gøre, er variabelt. Den omdøber også kolonnerne, som du har ønsket i den oprindelige funktion:
library(RMySQL)
## Open database:
mydb = dbConnect(MySQL(), user='root', password='', dbname='DataBase')
## Create function to get values:
GetVals <- function(TableNames) {
query <- paste0("SELECT ", Tables[1], ".Chr AS chrom, ", Tables[1], ".start AS site, ")
query <- paste0(query, paste0(Tables, ".methylation AS ", Tables, collapse=", "))
query <- paste0(query, " FROM ", Tables[1], paste0(" JOIN ", Tables[-1], " ON ", Tables[1], ".Chr=", Tables[-1], ".Chr AND ", Tables[1], ".start=", Tables[-1], ".start", collapse=""))
rs <- dbSendQuery(mydb, query)
data <- fetch(rs, n=-1)
return(data)
}
Tables <- c("Table1", "Table2", "Table3", "Table4")
my_data <- GetVals(Tables)
Dette er forespørgslen til Tables
variabel ovenfor:
> query
[1] "SELECT Table1.Chr AS chrom, Table1.start AS site, Table1.methylation AS Table1, Table2.methylation AS Table2, Table3.methylation AS Table3, Table4.methylation AS Table4 FROM Table1 JOIN Table2 ON Table1.Chr=Table2.Chr AND Table1.start=Table2.start JOIN Table3 ON Table1.Chr=Table3.Chr AND Table1.start=Table3.start JOIN Table4 ON Table1.Chr=Table4.Chr AND Table1.start=Table4.start"