You can use outer() but you have to vectorize the inner function:
X <- c("vijay","raj","joy")
Y <- c("maths","eng","science","social","hindi","physical","sanskrit")
set.seed(24)
marks <- data.frame(name = sample(X, 100, replace = TRUE),
subject = sample(Y, 100, replace = TRUE), stringsAsFactors = FALSE)
sset <- function(x,y) subset(marks, name == x & subject == y)
L <- outer(X, Y, FUN=Vectorize(sset, SIMPLIFY=FALSE))
L[1,1]
The object L is a matrix of dataframes.
Here is another solution using a double lapply():
L2 <- lapply(X, function(x) lapply(Y, function(y) subset(marks, name == x & subject == y)))
The object L2 is a list of lists.
Here is a variant with for-loops:
df <- vector("list", length(X)*length(Y))
l <- 1
for (i in X) for (j in Y) {
df[[l]] <- subset(marks, name == i & subject == j)
l <- l+1
}
For subsetting only for existing levels you can simply use split()
L3 <- split(marks, list(marks$name, marks$subject))
The objekt L3 is a list of dataframes.
outer()... or a doublelapply()