Pretty simple: I'm trying to create a sequence of crosstabs. I thought all I needed was a for-loop and xtabs
, but that hasn't worked out.
Say I have dataframe df
, a list of column names list1
and a second list list2
. I have written the following loop:
for (i in list1) {
for (j in list2) {
print(prop.table(xtabs(~i j,data=df),margin=2))}
}
However, when I run the loops, R spits out the following:
i1 j1 1
i1 j2 1
i1 j3 1
...
Why is this happening? If I write a standalone
prop.table(xtabs(~i j,data=df),margin=2)
with a certain i
and j
, I receive the table I'm looking for. Why does it break when I try to iterate the process?
CodePudding user response:
It sounds like you have i
and j
as character values from list1
and list2
. If that is true, you will need to build your formula from those values, such as with as.formula
or reformulate
. You can use paste
to put together the formula so identical to what you have with your example.
for (i in list1) {
for (j in list2) {
print(prop.table(xtabs(formula = as.formula(paste("~", i, " ", j)), data = df), margin = 2))
}
}
Or alternatively can use in your loop:
print(prop.table(xtabs(formula = reformulate(c(i, j)), data = cgd), margin = 2))