Home > Software design >  Replacing a subset of table values with a list of vectors
Replacing a subset of table values with a list of vectors

Time:07-08

I have a table as follows:

tableA <- structure(c(1L, 0L, 0L, 0L, 0L, 6L, 0L, 6L, 0L, 3L, 0L, 0L, 0L, 0L, 1L), dim = c(3L, 
                                                                   5L), dimnames = structure(list(c("X", "Y", 
                                                                                                    "Z"), c("A", "B", "C","D", "E")), names = c("", "")), class = "table")

    A B C D E
  X 1 0 0 3 0
  Y 0 0 6 0 0
  Z 0 6 0 0 1 

And a list of vectors as follows:

    listB <- list(
        "X" = c(0, 0, 0, 4, 0),
        "Y" = c(0, 0, 5, 0, 0),
        "Z" = c(0, 7, 0, 0, 0))

I would like to replace all values in table A, of columns B,C, and D, that are bigger than zero, with the corresponding values of list B.

Desired output:

    A B C D E
  X 1 0 0 4 0
  Y 0 0 5 0 0
  Z 0 7 0 0 1 

Is there any way to copy these values in such manner?

CodePudding user response:

You could do the following

cols2replace  = match(c('B', 'C', 'D'), colnames(tableA))
cells2replace = tableA[, cols2replace] > 0
    
tableB = matrix(unlist(listB), nrow = 3, byrow = TRUE)
tableA[, cols2replace][cells2replace] = tableB[, cols2replace][cells2replace]

> tableA
   
    A B C D E
  X 1 0 0 4 0
  Y 0 0 5 0 0
  Z 0 7 0 0 1

CodePudding user response:

Base R solution:

dfA <- as.data.frame.matrix(tableA)

ir <- data.frame(
  Map(function(x, y){ifelse(x > 0, y, x)},
    dfA,
    t(as.data.frame(listB))
  ),
  row.names = row.names(tableA)
)

col_idx <- !(colnames(ir) %in% c('B', 'C', 'D'))

ir[,col_idx] <- dfA[,col_idx]
  • Related