如何在 for 循环中向数据框添加变量?
我想创建一个数据框,其中每列是 2009 年至 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))
}