Function to read file via ODBC

Asked

Viewed 78 times

2

Hello, it must be a very simple problem, but I’ve searched a lot and I couldn’t find a solution to my question.

My setting is:

    R version 3.3.1 (2016-06-21)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows >= 8 x64 (build 9200)

locale:
[1] LC_COLLATE=Portuguese_Brazil.1252  LC_CTYPE=Portuguese_Brazil.1252    LC_MONETARY=Portuguese_Brazil.1252 LC_NUMERIC=C                      
[5] LC_TIME=Portuguese_Brazil.1252    

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

loaded via a namespace (and not attached):
[1] tools_3.3.1  rpart_4.1-10

I made a function to import files via ODBC from an ACCESS database, as follows:

importa.sql <- function(arquivo)
  {
    library(RODBC) # carrega pacote para conectar ao ODBC
    con <- odbcConnect("CarteiraComercialLocal") # cria a conexão local
    qry<-paste("(","SELECT * FROM ",arquivo,")")
    arquivo <- sqlQuery(con,qry,stringsAsFactors=FALSE) # Importa o arquivo para o data.frame do R
  }

I tested every line of the function and the code works perfectly. The problem is that when I run the function, the file is not available in R, but gives no error!!!

Does anyone know what might be going on?

1 answer

1


You are not returning the file in the function...

Add a line at the end of the function return(arquivo).

When calling the function use dados <- importa.sql()

  • Thanks @Daniel, I had already tested this, but it returns the result on the console. I would like him to create the data.frame and be available for use in another procedure. The files are very large and is unviable this way. Some other idea?

  • See the edit. The right way to do functions in R is for them to return an object and not for them to modify the global environment. You can use the operator <<- also kind arquivo <<- sqlQuery... but this is not recommended.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.