📜  在 R 编程中获取或设置向量的结构 - structure()函数

📅  最后修改于: 2022-05-13 01:54:18.343000             🧑  作者: Mango

在 R 编程中获取或设置向量的结构 - structure()函数

R 语言中的structure()函数用于通过改变向量的维度来获取或设置向量的结构。

示例 1:

# R program to get
# the structure of a Vector
  
# Creating a Vector
# of Numbers
x1 <- c(1:10)
structure(x1)
  
# Creating a vector 
# of strings
x2 <- c("abc", "cde", "def")
structure(x2)

输出:

[1]  1  2  3  4  5  6  7  8  9 10
[1] "abc" "cde" "def"

示例 2:

# R program to change 
# the structure of a Vector
  
# Creating a Vector
x <- c(1:10)
x
  
# Changing the structure of vector
y1 <- structure(x, dim = c(2, 5))
y2 <- structure(x, dim = c(5, 2))
y1
y2

输出:

[1]  1  2  3  4  5  6  7  8  9 10
     [, 1] [, 2] [, 3] [, 4] [, 5]
[1, ]    1    3    5    7    9
[2, ]    2    4    6    8   10
     [, 1] [, 2]
[1, ]    1    6
[2, ]    2    7
[3, ]    3    8
[4, ]    4    9
[5, ]    5   10