Skip to content
Prev 343121 / 398506 Next

populating matrix with binary variable after matching data from data frame

This is what I got:
A B C D
A 0 0 0 0
B 0 0 0 0
C 0 0 0 0
D 1 0 0 0
V2
V1  A B C D
  A 0 0 0 0
  B 0 0 0 0
  C 0 0 0 0
  D 1 0 0 0

I think you should sort out how your attempts went wrong.

My original 'f' assumed, perhaps foolishly, that x1 had columns names
"V1" and "V2",
perhaps it should have said just i<-as.matrix(x1) and checked that the result
was a 2-column matrix of character data.  E.g.,
f <- function (x, x1, badEntryAction = c("error", "omitRows", "expandX"))
{
    badEntryAction <- match.arg(badEntryAction)
    i <- as.matrix(x1)
    stopifnot(is.character(i), ncol(i)==2)
    if (badEntryAction == "omitRows") {
        i <- i[is.element(i[, 1], dimnames(x)[[1]]) &
               is.element(i[, 2], dimnames(x)[[2]]), , drop = FALSE]
    }
    else if (badEntryAction == "expandX") {
        extraDimnames <- lapply(1:2, function(k) setdiff(i[,
            k], dimnames(x)[[k]]))
        # if you want the same dimnames on both axes,
        # take union of the 2 extraDimnames
        if ((n <- length(extraDimnames[[1]])) > 0) {
            x <- rbind(x, array(0, c(n, ncol(x)),
                       dimnames = list(extraDimnames[[1]], NULL)))
        }
        if ((n <- length(extraDimnames[[2]])) > 0) {
            x <- cbind(x, array(0, c(nrow(x), n), dimnames = list(NULL,
                extraDimnames[[2]])))
        }
    }
    x[i] <- 1
    x
}

Bill Dunlap
TIBCO Software
wdunlap tibco.com


On Thu, Aug 14, 2014 at 8:15 AM, Adrian Johnson
<oriolebaltimore at gmail.com> wrote: