R语言 获取或设置向量的结构– structure() 函数
R语言中的 structure() 函数用于通过改变向量的尺寸来获取或设置其结构。
语法: structure(vec, dim)
参数:
vec: 矢量
dim: 新尺寸
例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