让我们考虑以下字符向量:
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")
我想知道R中是否有任何工具/功能允许我生成基于 M1 , M2的值下表em>, M3 和 M4 ,然后绘制表:
任何帮助将不胜感激!谢谢!
答案 0 :(得分:2)
此命令创建一个带有零和一的表。
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
如果你真的想拥有x
,你可以使用:
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
根据您的评论。如何摆脱var
和ind
以及如何使用列表:
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