[R] populating matrix with binary variable after matching data from data frame

William Dunlap wdunlap at tibco.com
Wed Aug 13 18:51:37 CEST 2014


You can replace the loop
> for (i in nrow(x1)) {
>    x[x1$V1[i], x1$V2[i]] <- 1;
> }
by
f <- function(x, x1) {
  i <- as.matrix(x1[, c("V1","V2")]) # 2-column matrix to use as a subscript
  x[ i ] <- 1
  x
}
f(x, x1)

You will get an error if not all the strings in the subscript matrix
are in the row or
column names of x.  What do you want to happen in this case.  You can choose
to first omit the bad rows in the subscript matrix
    goodRows <- is.element(i[,1], dimnames(x)[1]) &  is.element(i[,2],
dimnames(x)[2])
    i <- i[goodRows, , drop=FALSE]
    x[ i ] <- 1
or you can choose to expand x to include all the names found in x1.

It would be good if you included some toy data to better illustrate
what you want to do.
E.g., with
  x <- array(0, c(3,3), list(Row=paste0("R",1:3),Col=paste0("C",1:3)))
  x1 <- data.frame(V1=c("R1","R3"), V2=c("C2","C1"))
the above f() gives
> f(x, x1)
    Col
Row  C1 C2 C3
  R1  0  1  0
  R2  0  0  0
  R3  1  0  0
Is that what you are looking for?



More information about the R-help mailing list