RODBC: chars and numerics converted aggressively (with/without as.is)

前端 未结 1 1271
悲&欢浪女
悲&欢浪女 2021-01-06 02:59

Related to https://stackoverflow.com/a/33284035/3358272, I\'m finding inconsistent behavior with pulling data from SQL Server (2014).

library(RODBC)
sqlQuery         


        
相关标签:
1条回答
  • 2021-01-06 03:07

    If I understand correctly, I think this if what you are looking for,

    str(sqlQuery(
      .conn, 
      "SELECT * FROM r2test", 
      stringsAsFactors = FALSE,
      as.is = c(TRUE, FALSE)
    ))
    #'data.frame':  2 obs. of  2 variables:
    # $ mychar: chr  "1" "2"
    # $ mynum : num  3.14 6.28
    

    where as.is is specified as a logical vector (must have the same length as the number of columns in the result set). To be fair, this isn't really spelled out very well. The man page for sqlQuery just refers you to the as.is argument in read.table, which states:

    Note that as.is is specified per column (not per variable) and so includes the column of row names (if any) and any columns to be skipped.

    The downside of this approach is that you need to know in advance which columns you want to convert and which you don't. Personally I don't see why the default behavior isn't to just map SQL character types to R character types, SQL numeric types to R numeric types, etc, but perhaps there is a good reason for this on the backend. Automatically converting '1', '2', ... to integers does not seem like much of a "feature" to me.

    0 讨论(0)
提交回复
热议问题