Skip to content

factorDesign is not working #53

Description

@onahman

easy way to reproduce the bug:
toy_df = data.frame(x=c(1,2,3,4,5),y=as.factor(c(0,0,1,2,0)), z=c(10.23,19,20.42,12,1.221), w = as.factor(c(0,0,1,1,0)))
factorDesign(toy_df)

The resulting error:
Error in colnames<-(*tmp*, value = *vtmp*) : attempt to set 'colnames' on an object with less than two dimensions

I suggest the following corrections. it seem to work now:
factor.inds <- sapply(df[1, ], is.factor)
factor.labels <- which(factor.inds)
nfacs <- sum(factor.inds)
nlevs <- sapply(df[1, factor.inds], function(fac) nlevels(fac))
totnlevs <- sum(nlevs)
num.num = indcounter = ncol(df) - nfacs
x <- matrix(nrow = nrow(df), ncol = totnlevs + num.num)
colnames(x) <- 1:ncol(x)
index <- integer(ncol(x))
varnames <- character(ncol(df))
if (num.num > 0) {
x[, 1:num.num] <- as.matrix(df[, !factor.inds])
varnames[1:num.num] = colnames(x)[1:num.num] <- colnames(df)[!factor.inds]
index[1:num.num] <- 1:num.num
#indcounter <- indcounter + num.num - 1
}
for (j in 1:nfacs) {
submat <- model.matrix(~df[, factor.labels[j]] - 1)
indcounter <- indcounter + 1
submatinds <- indcounter:(indcounter + nlevs[j] - 1)
indcounter <- indcounter + nlevs[j] - 1
colnames(x)[submatinds] <- paste0(colnames(df)[factor.labels[j]], ":", 1:nlevs[j])
varnames[num.num + j] <- colnames(df)[factor.labels[j]]

x[, submatinds] <- submat
index[submatinds] <- num.num + j
}
attr(x, "varnames") <- varnames

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions