Jeff Keller Jeff Keller - 1 month ago 20
R Question

R data.table convert factor to logical in one step

Is it possible to convert my factor column

X
to a logical column in one step using data.table's "in-place" methods?

myDT <- data.table(X = factor(c("true", "false")))
str(myDT)

myDT[, X := as.logical(X)] # does not work

myDT[, X := as.logical(as.character(X))] # does not work either

# but this does
myDT[, X := as.character(X)]
myDT[, X := as.logical(X)]
str(myDT)

Answer

In R, logical means TRUE/FALSE and not true/false

library(data.table)#1.9.7+
myDT[, X:= X=="true"]
str(myDT)
#Classes ‘data.table’ and 'data.frame':  2 obs. of  1 variable:
# $ X: logi  TRUE FALSE
Comments