My goal is to create a list with each element containing a dataframe.
The dataframes are created by calling sqldf iteratively.
An example of what I want to do is this:
I have a vector names containing the names of my list.
> names
[1] "hello" "world"`
The list is called L, and is of length length(names).
Right now, L looks like this
> L
[[1]]
[1] 0
[[2]]
[1] 0
I want it to look like:
> L
$hello
Year Total
1 2000 100
2 2001 200
$world
Year Total
1 2000 150
2 2001 250
The first element L$hello is created by calling
names(L)[1] <- "hello"
L$hello <- sqldf(select Year, sum(case when names='hello' then Nums) as Total from Data group by Year")
Similarly, the second element L$world is created by replacing "'hello'" in that function call with "'world'".
However, this is a big problem if I have a lot of names.
My attempt to iterate this is here:
for (i in names) {
j=j+1
names(L)[j] <- i
L[[j]] <- sqldf("select Year, sum(case when names='names[names == i]' then Nums end) as 'Total' from Data group by Year")
}
The problem is definitely in the third line in the for loop where I have the names='names[names == i]' argument. How would I amend this?
I think it boils down to: How do I "paste" a string into a function call?
e.g. Instead of doing:
sqldf("select Year, sum(case when names='hello' then Nums end) as 'Total' from Data group by Year")
if I have a variable x where x <- "hello", how would I "paste" x into the sqldf function?