処理するテーブルの数が可変であると仮定すると、これはより一般的です。また、元の関数で必要な方法で列の名前を変更します。
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)
これは、Tables
に対して生成されたクエリです。 上記の変数:
> 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"