-3

How can I create variables and strings using the value passed by the loop?


Example

I have a set of countries = c('USA','Canada','Mexico').

I have a dataframe 'population'.

I want to query my database to get their population, and assign it to a column in a data frame. Don't worry about accessing the database, I am only concerned with dynamically creating the query string and the dataframe column name.

for (country in countries) {
   query = "SELECT population FROM population_database WHERE location='country';"
   population$country = mysql_query(query) 
}
4

3 回答 3

5

您可能正在寻找该paste功能。

x <- "USA"
paste("location =", x)
#[1] "location = USA" 
于 2012-08-04T19:32:17.270 回答
2

现在,如果您想创建一个 for 循环然后创建新的字符串名称,您可以这样做

a=c()
for (i in 1:5) {
    d=paste("location = ", i)
    a=c(a,d)
}

因此,

在此处输入图像描述

于 2018-08-25T15:07:30.857 回答
1

你想要population[[country]]而不是population$country. 该$符号是[[“两点之间的最长距离是一条捷径”的捷径。

其他已经提到的pasteand past0,你也可以使用sprintforgsubfn包。

于 2012-08-04T21:55:18.147 回答