![](/img/trans.png)
[英]Is there a way to create a data frame from two vectors to find all of the possible combinations between the vectors? (In r)
[英]r: create data frame with all possible options and number of variable combinations
这个问题可能很明显,或者已经问过,但是我找不到解决方案:
我想创建一个具有所有可能组合(和变量数量)的数据框,使其看起来像以下示例:
dataframe <- data.frame(variable = 1:4,
a = c("gender", NA, NA, NA),
b = c("age", NA, NA, NA),
c = c("city", NA, NA, NA),
d = c("education", NA, NA, NA),
e = c("gender", "age", NA, NA),
f = c("gender", "city", NA, NA),
g = c("gender", "education", NA, NA),
h = c("age", "city", NA, NA),
i = c("age", "education", NA, NA),
j = c("city", "education", NA, NA),
k = c("gender", "age", "city", NA),
l = c("gender", "age", "education", NA),
m = c("gender", "city", "education", NA),
n = c("gender", "age", "city", "education"))
我有太多的变量,所以不值得写出来,我想避免错误。 感谢您的帮助!
这是combn
一个选项。 获取vector
变量名,遍历序列vector
,施加combn
的vector
与m
指定为循环序列,转换为data.frame
和cbind
所有的list
元素结合在一起。 cbind.fill
的rowr
适用于用NA
fill
行数少于最大行data.frame
list
元素
library(rowr)
res <- do.call(cbind.fill, c(fill = NA, lapply(seq_along(v1), function(i) {
m1 <- combn(v1, i)
if(is.vector(m1)) as.data.frame.list(m1) else as.data.frame(m1)})))
colnames(res) <- letters[seq_along(res)]
或按照@Moody_Mudskipper的建议,
res1 <- do.call(cbind.fill, c(fill = NA, lapply(seq_along(v1), function(i) combn(v1, i))))
colnames(res1) <- letters[seq_len(ncol(res1))]
v1 <- c('gender', 'age', 'city', 'education')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.