[R-sig-DB] character to factor transform in package RpgSQL
Xiaobo Gu
gux|@obo1982 @end|ng |rom gm@||@com
Sun Nov 14 12:59:34 CET 2010
Hi Seth,
You are right, I have change the fetch function to this:
setMethod("fetch", signature(res="pgSQLResult", n="numeric"),
def=function(res, n, stringsAsFactors = TRUE, ...) {
cols <- .jcall(res using md, "I", "getColumnCount")
if (cols < 1) return(NULL)
l <- list()
for (i in 1:cols) {
ct <- .jcall(res using md, "I", "getColumnType", i)
l[[i]] <- if (ct == -5 | ct ==-6 | (ct >= 2 & ct <= 8)) {
numeric()
} else if (ct == 91) {
structure(numeric(), class = "Date")
} else if (ct == 93) {
structure(numeric(), class = class(Sys.time()))
} else character()
names(l)[i] <- .jcall(res using md, "S", "getColumnName", i)
}
j <- 0
while (.jcall(res using jr, "Z", "next")) {
j <- j + 1
for (i in 1:cols) {
l[[i]][j] <- if (is.numeric(l[[i]])) {
l[[i]][j] <- .jcall(res using jr, "D", "getDouble", i)
} else if (inherits(l[[i]], "Date")) {
tentativeDate <- .jcall(res using jr, "S", "getString", i)
if (length(tentativeDate) == 0 || tentativeDate == "0001-01-01
BC") tentativeDate <- NA
l[[i]][j] <- as.Date(tentativeDate)
} else {
a <- .jcall(res using jr, "S", "getString", i)
l[[i]][j] <- if (is.null(a)) NA else a
}
}
if (n > 0 && j >= n) break
}
if (j)
as.data.frame(l, row.names=1:j, stringsAsFactors = stringsAsFactors )
else
as.data.frame(l, stringsAsFactors = stringsAsFactors)
})
On Sun, Nov 14, 2010 at 12:52 PM, Seth Falcon <seth using userprimary.net> wrote:
> Hi,
>
> On Sat, Nov 13, 2010 at 8:28 PM, Xiaobo Gu <guxiaobo1982 using gmail.com> wrote:
>> Hi,
>> I have looked at the source code of package RpgSQL, it seems the fetch
>> function does not transform character column into factors, but when I
>> use the class function to test the result data frame of function
>> fetch, it all tells factor, can you help identify which part of the
>> function doing the transformation, in our usage we want to keep some
>> character column just as characters, bellowing is the source code of
>> function fetch in package RpgSQL.
>
> A guess is that you are seeing the default behavior of data.frame (and
> likely also as.data.frame) in transforming character vectors into
> factors.
>
> So I would suggest experimenting with this last bit:
>> if (j)
>> as.data.frame(l, row.names=1:j)
>> else
>> as.data.frame(l)
>> })
>
> For example:
>
> > sapply(as.data.frame(letters[1:3]), class)
> letters[1:3]
> "factor"
> > sapply(as.data.frame(letters[1:3], stringsAsFactors=FALSE), class)
> letters[1:3]
> "character"
>
>
> + seth
>
>
> --
> Seth Falcon | @sfalcon | http://userprimary.net/
>
More information about the R-sig-DB
mailing list