r - Appending to a text file in a loop -
r - Appending to a text file in a loop -
i have info frame called metricsinput looks this:
id extractname dimensions metrics first_ind 124 extract1.txt ga:date gs:sessions 1 128 extract1.txt ga:date gs:sessions 0 134 extract1.txt ga:date gs:sessions 0 124 extract2.txt ga:browser ga:users 1 128 extract2.txt ga:browser ga:users 0 134 extract2.txt ga:browser ga:users 0
i'm trying utilize above info frame in loop run series of queries, create 2 text files, extract1.txt , extract2.txt. reason have first_ind field want append column headings on first run through each unique file.
here's loop -- issue i'm having info each id not appending -- seem overwriting results, not appending. did go wrong?
for(i in seq(from=1, to=nrow(metricsinput), by=1)){ id <- metricsinput[i,1] myresults <- ga$getdata(id,batch = true, start.date="2013-12-01", end.date="2014-01-01", metrics = metricsinput[i,4], dimensions = metricsinput[i,3]) appendcolheads <- ifelse(metricsinput[i,5]==1, true, false) write.table(myresults, file=metricsinput$extractname[i], append=true, row.names = false, col.names = appendcolheads, sep="\t") }
although can code work, doesn't right approach @ all. @mrflick said in comments it's hard help without beingness able reproduce problem, along next lines
getdata <- function(id, metric, dim) { d <- ga$getdata(id, batch = true, start.date="2013-12-01", end.date="2014-01-01", metrics = metric, dimensions = dim) d$id <- id d } myresults <- map(getdata, id = metricsinput$id, metric = metricsinput$metrics, dim = metricsinput$dimensions)
this give list ith component output of ith iteration in loop. have split in 2 write in files wanted
myresultslist <- split(myresults, metricsinput$extractname) myresultslist <- lapply(myresultslist, do.call, = rbind) map(write.table, x = myresultslist, file = names(myresultslist), row.names = false, sep = "\t")
r
Comments
Post a Comment