简体   繁体   中英

r dbWriteTable in loop

I have many table that I am saving to a MariaDb in AWS RDS. I can manually save the tables. However I want to create a loop to do and I can't figure out the syntax on the dbWriteTable command. library(RMySQL)

dbWriteTable(con, "Account" , Account, overwrite = T)
dbWriteTable(con, "Campaign",  Campaign, overwrite = T)
dbWriteTable(con, "Contact" , Contact, overwrite = T)
dbWriteTable(con, "User", User, overwrite =T)

Instead I would like to do it in a loop.

nm = c("Account", "Campaign", "Contact",  "User")

for (i in 1:length(nm)) {

  dbWriteTable(con,  nm[i], paste(nm[i]), overwrite = TRUE)
 }

Per comments above, using get0 instead of paste like so will work:

nm = c("Account", "Campaign", "Contact",  "User")

for (i in 1:length(nm)) {
    dbWriteTable(con,  nm[i], get0(nm[i]), overwrite = TRUE)
}

Try this instead:

for (i in nm){
  dbWriteTable(con,  i, paste(i), overwrite = TRUE)
}

You do not need to extract the i from the original list with brackets, because i represents directly that object in the list. Essentially you are saying for each instance in nm, write to the db table named i (which will be one of the words in your list) and paste the value of i as the name.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM