Skip to content
Prev 377836 / 398502 Next

convert columns of dataframe to same factor levels

You can abuse the S4 class system to do this.

setClass("Size") # no representation, no prototype
setAs(from="character", to="Size", # nothing but a coercion method
  function(from){
    ret <- factor(from, levels=c("Small","Medium","Large"), ordered=TRUE)
    class(ret) <- c("Size", class(ret))
    ret
  })
z <- read.table(colClasses=c("integer", "Size"), text="7 Medium\n5 Large\n3
Large")
dput(z)
#structure(list(V1 = c(7L, 5L, 3L), V2 = structure(c(2L, 3L, 3L
#), .Label = c("Small", "Medium", "Large"), class = c("Size",
#"ordered", "factor"))), class = "data.frame", row.names = c(NA,
#-3L))

I wonder if this behavior is intended or if there is a more sanctioned way
to get read.table(colClasses=...) to make a factor with a specified set of
levels.

Bill Dunlap
TIBCO Software
wdunlap tibco.com


On Wed, Dec 19, 2018 at 3:19 AM Duncan Murdoch <murdoch.duncan at gmail.com>
wrote: