Unique combinations of all variables

妖精的绣舞 提交于 2019-12-25 11:58:12

问题


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])

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

Could someone please help me with this please?


回答1:


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

You could have done

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

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))

Or if the columns are already unique

 do.call(expand.grid, CRmarch30)

Or using 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))


来源:https://stackoverflow.com/questions/27264952/unique-combinations-of-all-variables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!