我刚刚在几年之后回到R的土地上,并且遇到了一个问题,即通过一个带有sqlSave的循环传递变量。我已经在Win7盒子上运行了RODBC和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”部分工作。有没有办法做我正在尝试使用自动增量字段(或基于第二个列表的字段)?
答案 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)