Using a looping structure in BASE R, I was wondering how I could make a data.frame
out of any two same-name variables in data.frames X
and Y
and then table
each data.frame?
Without a looping structure, my R code is:
X <- data.frame(R = rbinom(20, 1, .4), B = rbinom(20, 3, .3), N = rbinom(20, 5, .7))
Y <- data.frame(R = rbinom(20, 1, .4), B = rbinom(20, 3, .3), N = rbinom(20, 5, .7))
table(data.frame(X$R, Y$R))
table(data.frame(X$B, Y$B))
table(data.frame(X$N, Y$N))
We can use Map
to create the table
of corresponding columns of 'X' and 'Y'
Map(table, X, Y[names(X)])
If we need to have the levels same
Map(function(x, y) table(factor(x, levels = 0:5),
factor(y, levels = 0:5)), X, Y[names(X)])