Reputation: 154
So I am using the function aggregate for the marginalization of conditional probability tables, which works perfectly when used in the console line.
ab
x probs y
1 F 0.28 T
2 F 0.42 F
3 T 0.24 T
4 T 0.06 F
and use the following:
a = aggregate(probs ~ y , ab, sum)
produces:
a
y probs
1 F 0.48
2 T 0.52
which is exacly what I want the following custom function to do:
marginalizeFactor = function(A, margVar)
{
a = aggregate(probs ~ y + z, A, sum)
return(a)
}
margVar being a string with a character of the variable to be marginalized (for example magVar = "x").
My problem is, I don't know how to make this function work with any type of string character which is called (the function has to work not only with tables with variables "x" or "y", it could also be "fuel" etc).
And the function aggregate seems to not take strings or lists as a valid argument for grouping variable. HELP???? how to make the following:
marginalizeFactor = function(A, margVar)
{
a = aggregate(probs ~ magVar, A, sum)
return(a)
}
Being that margVar
is a string type (I mean, magVar
cannot be margVar = x
because the data type error pops up, so, margVar = "x"
)
Upvotes: 1
Views: 109
Reputation: 37641
In your second version, you have a typo. magVar -> margVar.
Yes, you cannot just use a string in the formula. you need something like this.
marginalizeFactor = function(A, margVar) {
a = aggregate(formula(paste("probs ~", margVar)), A, sum)
return(a)
}
marginalizeFactor(ab, 'y')
y probs
1 FALSE 0.48
2 TRUE 0.52
Actually, the function might be a little better as
marginalizeFactor = function(A, margVar) {
aggregate(formula(paste("probs ~", margVar)), A, sum)
}
Upvotes: 3