You can use lapply
for example like this :
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)
سؤال
I'm just now jumping back in the land of R after a few years away and am running into a problem passing variables through a loop with sqlSave. I've got RODBC up and running smoothly with MySQL on a Win7 box but can't seem to get my loops to work. Here's what data I have and what I'm trying to accomplish:
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)
The loops that I've tried to write, both to set up the data frames and to simplify the sqlSave statements, both failed to execute properly. Here's an example of one I tried that I thought would have worked:
i<-0
while (i<6) {
i<-i+1
a<-c("atbat","pitch","game","player","runner","umpire","coach")
b<-paste("mlb12$",a,sep="")
c[[i]]<-paste("test",i,sep="")
}
The problem with this loop is that I can't remember how (or figured out how) to use the c[[i]] incremental field to take the "b" values to create the data frame for each table from the list. I'm fairly certain if I could get this issue resolved I could get a loop to work for the "sqlSave" section. Is there a way to do what I'm trying to do with the autoincremental field (or with a field based on a second list)?
المحلول
You can use lapply
for example like this :
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)