How can you add variables to a dataframe in a for-loop?
I would like to create a dataframe where each column is the revenue for a region between 2009 and 2011.
regions = c('A','APAC','CEE','LATAM','ME', 'NA', 'WE')
# Loop through all regions, and add them as a column in my dataframe.
for (region in regions) {
# create the query string
query_string = sprintf("SELECT date, revenue
FROM country_revenue
WHERE region = '%s'
AND date>='2009-01-01'
AND date<='2011-12-31'
ORDER BY date ASC
LIMIT 2000", region)
# Query the database, and assign the result to a variable.
assign(sprintf('rev.%s',region), mysql_query(query_string))
# I only want the 2nd column returned from my query above.
# THIS IS THE PART THAT FAILS. Error in sprintf("rev.%s", region)[, 2] : incorrect number of dimensions
sprintf('rev.%s',region) = sprintf('rev.%s',region)[,2]
# Add this variable to my data frame.
revenue = cbind(revenue, sprintf('rev.%s',region))
}
cbindrather than the name of an object. (Although, even if it worked as is, the use ofassignand growing a data frame by appending columns one at a time are generally unwise.)dcastto go from "long" to "wide" format... is there a good reason for doing each query separately?