我试图使用以下代码来提供一堆变量的唯一组合表。
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))更多推荐
所有变量的唯一组合
发布评论