rdataframematrixmergecbind

Is there a way to multiply non-conformable arrays using 0 for missing values in R?


I am trying to figure out a way to multiply non-conformable arrays element-wise. I think this is a simple task, but I keep having problems.

I have two little tables:

> table_a

chr1 chr2 chr3 
   5    5    5 

and

> table_b

chr1 chr2 
   5    5 

I want to multiply these values element-wise, so that my output looks like:

> table c

chr1 chr2 chr3
  25   25    0

Using

table_a * table_b

works when both tables have the same number of elements, but I need this to work with files different numbers of elements.

I have tried converting the tables to data frames and using cbind, merge, and various joins, but keep running into issues. I am trying to use mostly base r or more robust libraries (like dplyr, etc.) but really trying to keep this as simple as possible. Any suggestions would be appreciated!

Here's my code:

# generating bed data
start1 <- seq(105000, 200000, by=20000)
stop1 <- start1+2000
chrs <- c("chr1", "chr2", "chr3")
x <- sort(rep(chrs, times=5))
df_a <- data.frame(chr=x, start=rep(start1,times=3), stop=rep(stop1,times=3))

start2 <-seq(800000, 920000, by=25000)
stop2 <- start2+2000

df_b <- data.frame(chr=x, start=rep(start2,times=3), stop=rep(stop2, times=3))
                   
# remove a chr from bed
df_b <- df_b[1:10,]
                   
                   
table_a <- table(df_a[,1])
table_b <- table(df_b[,1])

Solution

  • From the question table_b names are a subset of table_a names so:

    replace(0 * table_a, names(table_b), table_a[names(table_b)] * table_b)
    ## chr1 chr2 chr3 
    ##  25   25    0 
    

    If we can't assume that table_b names are a subset of table_a then use this:

    nms <- union(names(table_a), names(table_b))
    template <- setNames(numeric(length(nms)), nms)
    
    nms0 <- intersect(names(table_a), names(table_b))
    replace(template, nms0, table_a[nms0] * table_b[nms0]) |> as.table()
    ## chr1 chr2 chr3 
    ##  25   25    0