R sqlSave字符串变量循环问题

时间:2013-04-09 22:18:21

标签: mysql r loops rodbc

我刚刚在几年之后回到R的土地上,并且遇到了一个问题,即通过一个带有sqlSave的循环传递变量。我已经在Win7盒子上运行了RODBC和MySQL,但似乎无法使我的循环工作。这是我拥有的数据以及我想要实现的目标:

  • MLB使用pitchRX库保存为2012年的播放数据,将其保存为名为“mlb12”且具有多个表格的单个“值”
  • “mlb12”里面有七张桌子(atbat,球场,比赛,球员,跑垒员,裁判,教练)
  • 我想创建一个循环,为R中的每个表创建一个数据框,然后我可以通过一个循环使用sqlSave将它们插入我的MySQL数据库
  • 我已经将所有这些表插入到我的MySQL数据库中,但我是以“长”方式(即声明每个DF并为每个插入创建一个sqlSave语句)并且更愿意在两个循环中进行清理代码。
  • 下面是我目前要抓取这些数据并将其插入MySQL数据库的代码:

library(RODBC)

library(pitchRx)   

mlb12 <- scrapeFX(start = "2012-04-05", end = "2012-04-07",     
         tables=list(atbat=fields$atbat,pitch=fields$pitch,
         game=fields$game,player=fields$player,
         runner=fields$runner,umpire=fields$umpire,
         coach=fields$coach))

atbat <- mlb12$atbat
pitch <- mlb12$pitch
game <- mlb12$game
player <- mlb12$player
runner <- mlb12$runner
umpire<- mlb12$umpire
coach <- mlb12$coach

channel <- odbcConnect("db", uid = "cs", pwd = "pw")
sqlSave(channel,mlb12$atbat,tablename="atbat")
sqlSave(channel,mlb12$pitch,tablename="pitch")
sqlSave(channel,mlb12$game,tablename="game")
sqlSave(channel,mlb12$player,tablename="player")
sqlSave(channel,mlb12$runner,tablename="runner")
sqlSave(channel,mlb12$umpire,tablename="umpire")
sqlSave(channel,mlb12$coach,tablename="coach")
close(channel)  

library(pitchRx) mlb12 <- scrapeFX(start = "2012-04-05", end = "2012-04-07", tables=list(atbat=fields$atbat,pitch=fields$pitch, game=fields$game,player=fields$player, runner=fields$runner,umpire=fields$umpire, coach=fields$coach)) atbat <- mlb12$atbat pitch <- mlb12$pitch game <- mlb12$game player <- mlb12$player runner <- mlb12$runner umpire<- mlb12$umpire coach <- mlb12$coach channel <- odbcConnect("db", uid = "cs", pwd = "pw") sqlSave(channel,mlb12$atbat,tablename="atbat") sqlSave(channel,mlb12$pitch,tablename="pitch") sqlSave(channel,mlb12$game,tablename="game") sqlSave(channel,mlb12$player,tablename="player") sqlSave(channel,mlb12$runner,tablename="runner") sqlSave(channel,mlb12$umpire,tablename="umpire") sqlSave(channel,mlb12$coach,tablename="coach") close(channel)

我尝试编写的循环,无论是设置数据帧还是简化sqlSave语句,都无法正确执行。这是我尝试过的一个例子,我认为它会起作用:

这个循环的问题是我不记得如何(或弄清楚如何)使用c [[i]]增量字段来取“b”值来为每个表创建数据帧名单。我很确定如果我能解决这个问题我可以得到一个循环来为“sqlSave”部分工作。有没有办法做我正在尝试使用自动增量字段(或基于第二个列表的字段)?

1 个答案:

答案 0 :(得分:2)

您可以使用lapply,例如:

channel <- odbcConnect("db", uid = "cs", pwd = "pw")
a<-c("atbat","pitch","game","player","runner","umpire","coach")
lapply(a,function(x) 
     sqlSave(channel,mlb12[[x]],tablename=x)
close(channel)