I have a data frame similar to the example data frame below:
example = data.frame(
freq = c(22,1,12,4,8,76,55,43,1,34),
x=c("FALSE","FALSE","TRUE","FALSE","TRUE","TRUE","TRUE","FALSE","FALSE","TRUE"),
y=c("FALSE","FALSE","TRUE","FALSE","FALSE","TRUE","TRUE","TRUE","TRUE","TRUE")
)
If I do the normal table()
function on the last two columns, it would result in this, based on row frequencies:
> table(example$x,example$y)
FALSE TRUE
FALSE 3 2
TRUE 1 4
What I would like, however, is a function that adds together the values from the example$freq column of their respective row, ideally resulting in something like this:
FALSE TRUE
FALSE 27 44
TRUE 8 177
Is this possible with an existing function (also ideally being able to return tables of dimensions other than [2,2])?
This is, of course wouldn’t be an issue if there was a single row for each instance, e.g. 27 rows of FALSE FALSE pairs, etc., but that is not how my data is currently formatted.
If not possible with an existing function, any advice on creating the desired function?
camtastic is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
3
Any of these would work:
xtabs(freq ~ x + y, example)
xtabs(freq ~ ., example)
xtabs(example)
tapply(example[[1]], example[-1], sum)
library(tidyr)
example %>% uncount(freq) %>% table
with(example,
outer(
X = setNames(nm = unique(x)),
Y = setNames(nm = unique(y)),
FUN = Vectorize((X, Y) sum(freq[x == X & y == Y]))
)
)