I'm modifying some previous code I got thanks to @BrianDiggs: [](
Here's my reproducible code, as my actual code uses a data file and is much more involved based on various ifelse cases. This produces the same error:
First, unmodified and working
library(plyr)
df <- data.frame(name = LETTERS[1:3], var1 = c(1,5,10), var2 = c(2, 4, 6))
generator <- function(name, var1, var2) {
function(varA, varB) {
ifelse(varA + varB < 10,
10,
100)
}
}
funs <- mlply(df, generator)
interactions <- expand.grid(one = seq(0, 20, by=5), two = seq(0, 20, by=5))
table <- ldply(funs, function(f) {
data.frame(varA=interactions$one, varB=interactions$one,
result=f(interactions$one, interactions$two))
})
I don't really understand plyr
at all... but it's working. From my best guess, I create my input values and then plyr creates a sort of object with a function definition in it (funs
). Then I create my second layer of values and run the second function on the whole table of combinations.
Modified, not working
In any case, I want to have two different functions depending on cases. Here's what I tried:
library(plyr)
df <- data.frame(name = LETTERS[1:3], var1 = c(1,5,10), var2 = c(2, 4, 6))
generator <- function(name, var1, var2) {
ifelse(name == "A",
function(varA, varB) {
ifelse(varA + varB < 10,
10,
100)
},
function(varA, varB) {
varA + varB
})
}
funs <- mlply(df, generator)
interactions <- expand.grid(one = seq(0, 20, by=5), two = seq(0, 20, by=5))
table <- ldply(funs, function(f) {
data.frame(varA=interactions$one, varB=interactions$one,
result=f(interactions$one, interactions$two))
})
For this, I get, Error: Object of type 'closure' is not subsettable
I also tried doing the ifelse()
split inside the second function:
library(plyr)
df <- data.frame(name = LETTERS[1:3], var1 = c(1,5,10), var2 = c(2, 4, 6))
generator <- function(name, var1, var2) {
function(varA, varB) {
ifelse(name == "A",
"foo",
ifelse(varA + varB < 10,
10,
100))
}
}
funs <- mlply(df, generator)
interactions <- expand.grid(one = seq(0, 20, by=5), two = seq(0, 20, by=5))
table <- ldply(funs, function(f) {
data.frame(varA=interactions$one, varB=interactions$one, result=f(interactions$one, interactions$two))
})
For this, I get In '[<-.factor'('*tmp*', ... : invalid factor level, NAs generated
.
If I replace ifelse(name == "A")
with ifelse(0 < 1)
, I get, as expected all results as foo
. If I replace with ifelse(name == 1)
, I get all results of 10, which is odd because there's numerous cases where varA + varB > 10
.
Interestingly, I added another column to df
of criteria = c(1, 5, 10)
. I can't do ifelse(criteria > 1)
, but I can do ifelse(varA > criteria)
. Why wouldn't it allow a comparison to a static number, but it would allow for a comparison between row variables?
Anyway, my hope is to be able to do something like this:
generator <- function(var1, var2, ... , varN) {
function(varA, varB) {
ifelse(criteria based on any of var1 ... varN,
do a bunch of stuff,
do different stuff if criteria not met)
}
}