所有变量的唯一组合 [英] Unique combinations of all variables

查看:86
本文介绍了所有变量的唯一组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用以下代码来提供一堆变量的唯一组合表。

I have attempted to use the following code to come up with a table of unique combinations of a bunch of variables.

V1=as.vector(CRmarch30[1])
V2=as.vector(CRmarch30[2])
V3=as.vector(CRmarch30[3])
V4=as.vector(CRmarch30[4])
V5=as.vector(CRmarch30[5])
V6=as.vector(CRmarch30[6])
V7=as.vector(CRmarch30[7])

您可能已经猜到,CRmarch30是一个具有7列的数据框。我将每列转换为向量。然后,我使用以下代码创建了7个变量的所有唯一组合:

As you may have already guessed, CRmarch30 is a dataframe with 7 columns. I converted each column into a vector. Then, i used the following code to create all unique combination of the 7 variables:

combo=expand.grid(V1,V2,V3,V4,V5,V6,V7)
combo

而不是获得输出,我收到以下错误消息:

Instead of getting the output, I get the following error message:

 Warning message:
In format.data.frame(x, digits = digits, na.encode = FALSE) :
  corrupt data frame: columns will be truncated or padded with NAs

有人可以帮我吗?

推荐答案

as.vector 不会将其转换为 vector 例如:

The as.vector is not converting it to vector For example:

V1=as.vector(CRmarch30[1])
V2=as.vector(CRmarch30[2])
 V3=as.vector(CRmarch30[3])

expand.grid(V1, V2, V3)
#  Var1 Var2 Var3
#1    1    5    0
#Warning message:
#In format.data.frame(x, digits = digits, na.encode = FALSE) :
# corrupt data frame: columns will be truncated or padded with NAs

 is.vector(V1)
 #[1] FALSE
 is.data.frame(CRmarch30[1])
 #[1] TRUE

您可以做到的

 V1 <- CRmarch30[,1]
 is.vector(V1)
 #[1] TRUE

但是,您不需要创建 vector 对象。这可以通过(如果需要独特的组合来完成)

But, you don't need to create vector objects. This could be done by (if you need unique combinations)

 do.call(expand.grid,lapply(CRmarch30,unique))

或者如果列已经唯一

 do.call(expand.grid, CRmarch30)

或使用 data.table

 library(data.table)
 setDT(CRmarch30)[,do.call(CJ, lapply(.SD, unique))]



数据



data

set.seed(22)
CRmarch30 <- as.data.frame(matrix(sample(c(NA,0:5), 10*3,
                                    replace=TRUE), ncol=3))

这篇关于所有变量的唯一组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆