简体   繁体   中英

mapply with two lists and a data frame

I am trying to write a function for use within mapply that involves two lists and a data frame. I want to pick out several subsets of data indexed by the two lists (for row and column). Here's an example of what I want to do in a loop, and my attempt at the 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 that mapply is trying to apply this function to each column of d; how do I avoid this? If I were only indexing one dimension (.eg the row) and a single column, the equivalent using lapply would be:

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

The MoreArgs parameter expects a list containing the aditional parameters. Since a data.frame is a list, mapply thinks that the data.frame columns are the additional parameters and complains that the function doesn't use these. You need to wrap your data.frame in list . You also should set SIMPLIFY = FALSE to get a list returned.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM