如何將變量添加到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