Получение или установка структуры вектора в программировании на R - функция structure ()

Опубликовано: 17 Февраля, 2022

structure() function in R Language is used to get or set the structure of a vector by changing its dimensions.

Syntax: structure(vec, dim)

Parameters:
vec: Vector
dim: New Dimensions

Example 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»

Example 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