I open the question to have a reference of the available options, in Spanish.
Suppose we have a data set like the following:
set.seed(2018)
mi_df <- data.frame(stringsAsFactors = F,
var1 = rnorm(50),
"grupo1" = sample(c("a", "b", "c"), 50, TRUE),
"grupo2" = sample(c("x", "y", "z"), 50, TRUE))
The goal is to obtain the average of var1 using mean
, for each of the combinations of group1 and group2 (ax, bx, cx, ay, by, etc.).
One way is to nest lapply
, so that we apply the function mean
for each combination. The first lapply
will pass through the values of group1 and the second one, nested, by those in group2
lapply(unique(mi_df[["grupo1"]]), function(x) {
lapply(unique(mi_df[["grupo2"]]), function(y) {
subconjunto <- subset(mi_df, grupo1 == x & grupo2 == y)
mean(subconjunto[["var1"]])
})
})
The result is a list with nine results (actually, a list of three lists, with three results inside each one).
The above can become confusing with more complex problems.
How could I get the same nine results, but without nesting lapply
?