0

I want to simplify some code that I am running. I am trying to pull the dimensions of multiple datasets that result from SQL queries. I want to try to loop through the dataset names

I have been able to get my desired result, I'm just not sure it's the most efficient way of going about this: I have a separate SQL query line for each dataset.

This is the original code:

    library(sqldf)
    dim(sqldf("select Group1, count(*) as Count from Data1 group by Group1"))[1]
    dim(sqldf("select Group1, count(*) as Count from Data2 group by Group1"))[1]
    dim(sqldf("select Group1, count(*) as Count from DataN group by Group1"))[1]

This is my attempt at simplifying the code:

    datalist=c(Data1,Data2,...DataN)
    abc=vector("list",length(datalist))
    for (i in seq_along(datalist))
      abc[[i]]=dim(sqldf("select Group1, count(*) as Count from datalist[i] group by Group1"))[1]

I expect the output to show N numbers for each dataset but I get an error message that reads "no such table: datalist."

1 Answer 1

1

This is because the "datalist[i]" within the string does not get substituted by actual value of the datalist[i] variable, but passed on to SQL. Try

datalist=c("Data1", "Data2", ... "DataN")
queries <- sprintf("select Group1, count(*) as Count from %s group by Group1", datalist)
abc <- lapply(queries, function(q) {
           nrow(sqldf(q))
         })

Some additional remarks:

  • don't use for to populate a list, use lapply which directly generates the list
  • if you do, there is no need to initialize a list other than abc <- list()
  • don't use dim(x)[1], nrow is more explicit
  • if your data is always "Data1", "Data2"... etc, you can also do

    queries <- sprintf("select Group1, count(*) as Count from Data%d group by Group1", 1:10)
    
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.