所有变量的唯一组合

编程入门 行业动态 更新时间:2024-10-28 06:36:55
本文介绍了所有变量的唯一组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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

更多推荐

所有变量的唯一组合

本文发布于:2023-10-19 18:29:35,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1508380.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:组合   变量

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!