Skip to contents

The stm_swap...() set of functions swap the elements at specified indices in a vector, rows in a matrix or data frame, or columns in a matrix or data frame.

Usage

stm_swap_vector(dat, i, j)

stm_swap_rows(dat, i, j)

stm_swap_cols(dat, i, j)

Arguments

dat

The input vector, matrix, or data frame. In stm_swap_vector, it should be a vector. In stm_swap_rows and stm_swap_cols, it should be a matrix or data frame.

i

The index of the first element (or row/column) to swap.

j

The index of the second element (or row/column) to swap.

Value

A vector, matrix, or data frame with the specified elements swapped.

Examples

# vector
v <- c(1, 2, 3, 4, 5)
print(v)
#> [1] 1 2 3 4 5
stm_swap_vector(v, i = 2, j = 4)
#> [1] 1 4 3 2 5

# swap matrix rows
A <- matrix(1:9, ncol = 3, byrow = TRUE)
print(A)
#>      [,1] [,2] [,3]
#> [1,]    1    2    3
#> [2,]    4    5    6
#> [3,]    7    8    9
stm_swap_rows(A, 1, 3)
#>      [,1] [,2] [,3]
#> [1,]    7    8    9
#> [2,]    4    5    6
#> [3,]    1    2    3

# swap matrix columns
A <- matrix(1:9, ncol = 3, byrow = TRUE)
print(A)
#>      [,1] [,2] [,3]
#> [1,]    1    2    3
#> [2,]    4    5    6
#> [3,]    7    8    9
stm_swap_cols(A, 1, 3)
#>      [,1] [,2] [,3]
#> [1,]    3    2    1
#> [2,]    6    5    4
#> [3,]    9    8    7