user3390169
user3390169

Reputation: 1045

R using sapply for a function with multiple inputs

I can't figure out how to use sapply for a function with multiple inputs.

If I have a vector and two matrices, I want to feed the vector and one row of the matrix into the function at a time:

A<-cbind(1000, 1000, 4000, 1333, 2333, 2333)
B<-cbind(rnorm(100), rnorm(100), rnorm(100), rnorm(100),rnorm(100), rnorm(100))
C<-cbind(rep(1, 100), rep(2, 100), rep(3, 100), rep(4, 100),rep(5, 100),rep(6, 100))

myFunc <- function(A, B, C) {
    X<-A * (B - C)
    #X[which(X<0)]=0
    return(sum(X))
}

so, I should receive a vector of 100 sums from this operation.

I guess I don't understand the structures well enough. I used class() on the variables and found that A is a matrix (1x6), B is a matrix (20,000x6), and C is a data frame (2x6 but I only send the first row). when I use mapply(myFunc, A,B,C) I actually get a result but it is a column of 120k rows, not 20k like I was expecting

Is mapply applying my function to every element in B? Is there a way to make it operate only for each row?

Upvotes: 0

Views: 1244

Answers (1)

IRTFM
IRTFM

Reputation: 263311

You are mixing vector indexing with matrix column indexing, so use seq_along for the vector item and reference the column number in the matrices. I don;t think there is any R function that can read your mind for that goal.

A<-cbind(1000, 1000, 4000, 1333, 2333, 2333)
B<-cbind(rnorm(100), rnorm(100), rnorm(100), rnorm(100),rnorm(100), rnorm(100))
C<-cbind(rep(1, 100), rep(2, 100), rep(3, 100), rep(4, 100),rep(5, 100),rep(6, 100))

myFunc <- function(A, B, C) { X <- matrix(NA, nrow(B), ncol(B) )
   for (i in seq_along(A) ){
    X[, i] <-  A[i] * (B[, i] - C[,i])}
    X[ which(X<0)] = 0
   X   # if you do not want to collapse to single number, do NOT use `sum`
}

Upvotes: 2

Related Questions