Home > other >  Apply a function that takes two vectors as input to two matrices across their corresponding columns
Apply a function that takes two vectors as input to two matrices across their corresponding columns

Time:02-11

I have a function in R that takes two vectors and an integer like this:

MyFunction<-function(MyLoot, DungeonLoot, DungeonOrder)
{  

  # Perfect Match
  PerfectMatch = MyLoot[1]==DungeonLoot[1]
  
  # Group Match
  GroupandClassMatch = (MyLoot[2]==DungeonLoot[2])&(MyLoot[3]>=DungeonLoot[3])
  
  # Order Match
  OrderMatch = MyLoot[5]==DungeonOrder
  
  # Order Match  1
  OrderMatchPlusOne = (OrderMatch)&(MyLoot[8]==1)
  
  # Final Score
  Score = PerfectMatch*1   GroupandClassMatch*1   OrderMatch*2   OrderMatchPlusOne*1
  
  return(Score)
}

Now I want to apply MyFunction to two matrices Matrix1 and Matrix2 across their rows so that I have a vector that looks something like:

c(MyFunction(Matrix1[1,],Matrix2[1,],12),MyFunction(Matrix1[2,],Matrix2[2,],12),...,MyFunction[Matrix1[n,],Matrix2[n,],12)

What is the best (and most efficient) way of doing this? I could use a for loop but wondering if there is a better way e.g. using one of apply, sapply, mapply, lappy functions

CodePudding user response:

Your newly posted function is still easily vectorized:

MyFunction <- function(MyLoot, DungeonLoot, DungeonOrder) {  
  # Perfect Match
  PerfectMatch <- MyLoot[1,] == DungeonLoot[1,]
  
  # Group Match
  GroupandClassMatch <- (MyLoot[2,] == DungeonLoot[2,]) & (MyLoot[3,] >= DungeonLoot[3,])
  
  # Order Match
  OrderMatch <- MyLoot[5,] == DungeonOrder
  
  # Order Match  1
  OrderMatchPlusOne <- OrderMatch & (MyLoot[8,] == 1)
  
  # Final Score
  Score <- PerfectMatch   GroupandClassMatch   OrderMatch*2   OrderMatchPlusOne
  
  return(Score)
}

MyFunction(Matrix1, Matrix2, 12)

CodePudding user response:

An example data along with expected output would have helped to better understand the question. However, I think you don't need any loop or apply functions to do this. If you have input as matrix then you should be able to do this directly.

Try,

rowSums(Matrix1 == Matrix2)
#For only specific columns
#rowSums(Matrix1[, 1:2] == Matrix2[, 1:2])

CodePudding user response:

This achieved what I wanted - not sure if it is the most computationally efficient solution though.

t(mapply(function(x,y) MyFunction(x,y,11), split(MyLoot, col(MyLoot)), split(DungeonLoot, col(DungeonLoot))))
  • Related