R mapply vs bad lapple

I think I missed something simple here: I have a list of data.frames and a list of line numbers to select from. Something like that:

a <- data.frame(q = c(1,0,0,0), 
                w = c(1,1,0,0),
                e = c(1,1,1,0),
                r = c(1,1,1,1))
b <- a + 1
c <- a + 2
d <- a + 3

data <- list(a = a, b = b, c = c, d = d)

ind_a <- c(1, 2) 
ind_b <- c(1, 3)
ind_c <- c(1, 4)
ind_d <- c(2, 4)

train <- list(ind_a, ind_b, ind_c, ind_d) 

Now, I would like to select the rows, and I thought that the correct form could be

test1 <- mapply(function(x,y) x[y, ], data, train)

but the only way to make it work:

test2 <- lapply(1:4, function(x) data[[x]][train[[x]], ])

which seems to me fake for a loop ...

Where am I wrong ???

+6
source share
1 answer

With a mapplydefault option SIMPLIFY = TRUE, and it simplifies it to an array when the sizes are the same. If we change it to FALSE, the output will belist

mapply(function(x,y) x[y, ], data, train, SIMPLIFY = FALSE)

Or use a wrapper Map

Map(function(x, y) x[y, ], data, train)
+4
source

All Articles