nKandel
nKandel

Reputation: 2575

Concat String with variable value to form New Variable

I have to make dynamic variable which store different value as given in pseudo code

for(i in 1:30)
 "Day"+i <- sqldf("select * from call_details where day ="+i)

Is it possible in R or not and if possible then how? I just able to concat the string (using paste) which store the concated string as character but couldn't able to store value on it. Also I could not able to find out how to pass variable on sql query statement.

Upvotes: 1

Views: 6048

Answers (2)

thelatemail
thelatemail

Reputation: 93938

You should be storing similar data in a structure like a list instead of free floating variables. This might seem odd at first, but trust me when I say this will prevent a lot of grief further down the line. E.g.:

Days <- lapply(1:30,function(i) sqldf(paste("select * from call_details where day =",i)) )

Then you can access the components of the list like:

Days[[1]]
Days[[2]]
etc etc

Instead of using day1 day2 etc etc

Upvotes: 3

Thomas
Thomas

Reputation: 44565

You probably want to look into assign to be able to construct variables in the way you're describing. In general, you can use paste but you connect strings with commas, not pluses.

Something like the following:

for(i in 1:30)
    assign(paste0("Day",i), sqldf(paste("select * from call_details where day =",i)))

Upvotes: 1

Related Questions