Skip to content
Prev 319455 / 398506 Next

Modifying a data frame based on a vector that contains column numbers

Try looping over columns, as in

fDF <- function (x, column)
{
    stopifnot(length(dim(x))==2, all(column > 0), all(column <= ncol(x)), length(column) == nrow(x))
    u <- unique(column)
    tmp <- split(seq_along(column), factor(column, levels = u))
    for (i in seq_along(tmp)) {
        x[ tmp[[i]],  u[i] ] <- 1
    }
    x
}
c1 c2 c3
1  1 NA NA
2 NA  1 NA
3 NA NA  1
4 NA  1 NA
5  1 NA NA

If you use a matrix instead of a data.frame then the following works and is probably much quicker.
fMat <- function (x, column) 
{
    stopifnot(is.matrix(x), all(column > 0), all(column <= ncol(x)), length(column) == nrow(x))
    x[cbind(seq_len(nrow(x)), column)] <- 1
    x
}

Your problem may be better represented with sparse matrices (see the Matrix package).

Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com