Mapply with two lists and a dataframe

I am trying to write a function for use in mapply that includes two lists and a dataframe. I want to highlight multiple subsets of data indexed by these two lists (for row and column). Here is an example of what I want to do in a loop and my attempt at a function:

#simulated data and column, row indexes
set.seed(100)
d <- data.frame(matrix(1:100,nrow=10,ncol=10))
y <- lapply(vector("list", 5),function(x){sample(1:10,5)}) 
x <- as.list(c(1,3,5,7,9),length=5)

# version in loop
whatiwant <- list(length=5)
for (i in 1:5){
   whatiwant[[i]] <- d[y[[i]],x[[i]]]
}

fun <- function(x,y,d){d[y,x]}

whatiwant2 <- mapply(fun,y,x,MoreArgs=d)

      

From the error given, I suspect mapply is trying to apply this function to every d column; how can i avoid this? If I were only indexing one dimension (like a row) and one column, the equivalent using lapply would be:

onedim <- lapply(y,function(d,y){d[y]},d=d[,1])

      

+3


source to share


1 answer


The parameter MoreArgs

expects a list containing additional parameters. Since data.frame is a list, it mapply

considers the columns data.frame to be optional parameters and complains that the function doesn't use them. You need to wrap your data.frame file in list

. You must also set SIMPLIFY = FALSE

to get the list back.



whatiwant2 <- mapply(fun, y = y, x = x, MoreArgs=list(d), SIMPLIFY = FALSE)
#[[1]]
#[1]  7 10  4  6  3
#
#[[2]]
#[1] 21 29 26 27 30
#
#[[3]]
#[1] 48 47 45 42 50
#
#[[4]]
#[1] 62 70 69 67 66
#
#[[5]]
#[1] 86 90 89 88 81

      

+4


source







All Articles