欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

R 语言 expand.grid 示例说明

最编程 2024-03-18 09:22:58
...

expand.grid()R语言中的函数用于创建一个 DataFrame ,其中包含所有值,这些值可以通过作为参数传递给函数的所有向量或因子的组合形成。

用法: expand.grid(…)

参数:
……:向量 1、向量 2、向量 3、...

范例1:


# R program to create a dataframe
# with combination of vectors
  
# Creating vectors
x1 <- c("abc", "cde", "def")
x2 <- c(1, 2, 3)
x3 <- c("M", "F")
  
# Calling expand.grid() Function
expand.grid(x1, x2, x3)

输出:

   Var1 Var2 Var3
1   abc    1    M
2   cde    1    M
3   def    1    M
4   abc    2    M
5   cde    2    M
6   def    2    M
7   abc    3    M
8   cde    3    M
9   def    3    M
10  abc    1    F
11  cde    1    F
12  def    1    F
13  abc    2    F
14  cde    2    F
15  def    2    F
16  abc    3    F
17  cde    3    F
18  def    3    F

范例2:


# R program to create a dataframe
# with combination of vectors
  
# Creating vectors
x1 <- c("abc", "cde", "def")
x2 <- c(1, 2, 3)
x3 <- c("M", "F")
  
# Calling expand.grid() Function
expand.grid(x1, x3)

输出:

  Var1 Var2
1  abc    M
2  cde    M
3  def    M
4  abc    F
5  cde    F
6  def    F