Skip to content
Prev 343106 / 398506 Next

populating matrix with binary variable after matching data from data frame

I may have missed something, but I didn't see the result you want for
your example.  Also,
none of the entries in the x1 you showed are row or column names in x,
making it hard to show what you want to happen.

Here is a function that gives you the choice of
    *error: stop if any row of x1 is 'bad'
    *omitRows: ignore rows of x1 are 'bad'
    *expandX: expand the x matrix to include all rows or columns named in x1
(Row i of x1 is 'bad' if that x1[,1] is not a rowname of x or x1[,2]
is not a column name of x).

f
function (x, x1, badEntryAction = c("error", "omitRows", "expandX"))
{
    badEntryAction <- match.arg(badEntryAction)
    i <- as.matrix(x1[, c("V1", "V2")])
    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 Wed, Aug 13, 2014 at 2:33 PM, Adrian Johnson
<oriolebaltimore at gmail.com> wrote: