Milad
Milad

Reputation: 31

apply() function to columns of a matrix and elements of a numeric vector, respectively, in order

I have a function f(list,t) where the first argument is a list and the second one t is a number. I wanna apply f to columns of a matrix M and elements of a vector T respectively. Hence, if columns of M are (M_1,M_2,...,M_k) and T = (t_1,t_2,...,t_k), I want to get the following :

f(M_1,t_1), f(M_2,t_2), ..., f(M_k,t_k).

Is there an efficient way doing so without using for loop?

For example if

f <- function(list,x) {x %in% list}
M <- matrix(1:12,4,3)
T <- c(1,2,10)

I expect to get

TRUE FALSE TRUE

The following line applies f on each column of M and each element of T

apply(M,2,f,T)

But what I need is just the diagonal of this output, so I want a way to avoid extra computations.

Upvotes: 2

Views: 156

Answers (3)

YOLO
YOLO

Reputation: 21749

You can also use sapply using the number of columns in the matrix. Later, we use any to return True (if any) value from each column

Tr <- c(1,2,10)
sapply(seq(ncol(M)), function(x) any(f(M[,x], Tr)))

[1]  TRUE FALSE  TRUE

Upvotes: 3

Marat Talipov
Marat Talipov

Reputation: 13314

mapply(f,as.data.frame(M),T)

as.data.frame is needed to convert M to the list of the matrix columns, and mapply applies f to the produced list and vector T in a pairwise fashion.

Upvotes: 1

GordonShumway
GordonShumway

Reputation: 2056

Convert your matrix to a data frame and then use the map2 function from the purrr package:

library(tidyr)
df <- as.data.frame(M)
unlist(map2(df, t, f))

Also it is a terrible idea to name a variable T (or F) as that can cause a ton of problems with logical terms.

Upvotes: 2

Related Questions