如何将变量添加到for循环中的数据框中?将列添加到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))
}
我推测什么不起作用的事实是,您将字符串传递给'cbind'而不是对象的名称。 (虽然,即使它的工作原理是,使用'assign'并通过逐个添加列来增加数据框通常是不明智的。) – joran 2012-08-04 21:17:11
感谢Joran - 我不确定创建数据框的最佳方式使用for-loop。如果你有一个建议,请让我知道:) – 2012-08-04 21:20:22
最好的方法是不使用循环!在我看来,你应该能够使用所有区域进行查询并且更容易地在R中过滤。然后像'dcast'从“长”到“宽”格式......是否有单独做每个查询的好理由?确切地说,是 – Justin 2012-08-04 21:23:52