我因此有一段代码:
mydb <- dbConnect(MySQL(), user = "****", password = "****", dbname = "c_global", host = "")
df_ipt_rate_history <- fetch(dbSendQuery(mydb, "select * from ipt_rate_history"), n=-1)
df_map_occupation <- fetch(dbSendQuery(mydb, "select * from map_occupation"), n=-1)
df_map_titles <- fetch(dbSendQuery(mydb, "select * from map_titles"), n=-1)
df_pcode_full_areas <- fetch(dbSendQuery(mydb, "select * from pcode_full_areas"), n=-1)
df_pcode_rics_regions <- fetch(dbSendQuery(mydb, "select * from pcode_rics_regions"), n=-1)
df_pcode_sector_areas <- fetch(dbSendQuery(mydb, "select * from pcode_sector_areas"), n=-1)
...等等(多个表)
dbDisconnect(mydb)
它工作正常,但是有一种方法可以设置某种循环,从而可以通过单个命令读取数据库中的每个表(并输出到数据帧)?
谢谢
假设每个表具有不同的结构,一个选项是将每个数据帧存储在列表中,然后使用lapply
或purrr::map
来获取它们。
在基本R中:
mydb <- dbConnect(MySQL(), user = "****", password = "****", dbname = "c_global", host = "")
table_names <- c("ipt_rate_history",
"map_titles",
"pcode_full_areas",
"pcode_rics_regions",
"pcode_sector_areas")
df <- lapply(table_names,
function(x) fetch(dbSendQuery(mydb, paste("select * from", x), n = -1)))
df <- setNames(df, table_names)
带有purrr
包:
table_names <- c("ipt_rate_history",
"map_titles",
"pcode_full_areas",
"pcode_rics_regions",
"pcode_sector_areas")
df <- purrr::map(table_names,
~fetch(dbSendQuery(mydb, paste("select * from", .), n = -1)))
df <- purrr::set_names(df, table_names)
然后您可以使用df$table_name
,例如 df$ipt_rate_history
访问每个表。