Reputation: 8848
Let's consider the following character vectors:
M1 = c("Variable_1", "Variable_2", "Variable_3")
M2 = c("Variable_2", "Variable_4", "Variable_5")
M3 = "Variable_3"
M4 = c("Variable_1", "Variable_2", "Variable_3", "Variable_4", "Variable_5")
I was wondering if there is any tool/function in R that allows me to generate the following table based on the values of M1, M2, M3, and M4, and then plot the table :
Any help would be appreciated! Thanks!
Upvotes: 0
Views: 244
Reputation: 81713
This command creates a table with zeroes and ones.
table(do.call(rbind, lapply(c("M1", "M2", "M3", "M4"), function(x)
data.frame(ind = x, var = get(x)))))
var
ind Variable_1 Variable_2 Variable_3 Variable_4 Variable_5
M1 1 1 1 0 0
M2 0 1 0 1 1
M3 0 0 1 0 0
M4 1 1 1 1 1
If you really want to have x
s you can use:
tab <- table(do.call(rbind, lapply(c("M1", "M2", "M3", "M4"), function(x)
data.frame(ind = x, var = get(x)))))
replace(replace(tab, as.logical(tab), "x"), !tab, "")
var
ind Variable_1 Variable_2 Variable_3 Variable_4 Variable_5
M1 x x x
M2 x x x
M3 x
M4 x x x x x
Based on your comment. How to get rid of var
and ind
and how to use a list:
LL <- list(M1, M2, M3, M4)
tab <- table(do.call(rbind, lapply(seq_along(LL), function(x)
data.frame(ind = x, var = LL[[x]]))))
dimnames(tab) <- unname(dimnames(tab))
replace(replace(tab, as.logical(tab), "x"), !tab, "")
Variable_1 Variable_2 Variable_3 Variable_4 Variable_5
1 x x x
2 x x x
3 x
4 x x x x x
Upvotes: 2