Jeff Keller Jeff Keller - 1 year ago 92
R Question

R data.table convert factor to logical in one step

Is it possible to convert my factor column

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

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

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)]

Answer Source

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

myDT[, X:= X=="true"]
#Classes ‘data.table’ and 'data.frame':  2 obs. of  1 variable:
# $ X: logi  TRUE FALSE
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download