在 R 语言中更改矩阵的行和列值 - sweep()函数
在本文中,我们将学习在 R 编程语言中更改矩阵的行和列值。
R——sweep()函数
R语言中的sweep()函数用于对数据矩阵中的行或列进行“+或-”运算。它用于从数据框架中扫描值。
Syntax: sweep(x, MARGIN, STATS, FUN)
Parameters:
- x: Typically a matrix.
- MARGIN: MARGIN = 1 means row; MARGIN = 2 means column.
- STATS: the value that should be added or subtracted
- FUN: The operation that has to be done (e.g. + or -)
示例 1:扫描矩阵
R
# R program to illustrate
# sweep matrix
# Create example matrix
data <- matrix(0, nrow = 6, ncol = 4)
# Apply sweep in R
data_ex1 <- sweep(x = data, MARGIN = 1,
STATS = 5, FUN = "+")
# Print example 1
print(data_ex1)
R
# R program to illustrate
# sweep function with stats
# Create example matrix
data <- matrix(0, nrow = 6, ncol = 4)
# Sweep with Complex STATS
data_ex2 <- sweep(x = data, MARGIN = 1,
STATS = c(1, 2, 3, 4, 5, 6),
FUN = "+")
# Print example 2
print(data_ex2)
输出:
[,1] [,2] [,3] [,4]
[1,] 5 5 5 5
[2,] 5 5 5 5
[3,] 5 5 5 5
[4,] 5 5 5 5
[5,] 5 5 5 5
[6,] 5 5 5 5
在上面的代码中,矩阵的值为0,然后被sweep()函数扫描,矩阵的新值变为5。
示例 2:将 sweep() 与 stats 一起使用
R
# R program to illustrate
# sweep function with stats
# Create example matrix
data <- matrix(0, nrow = 6, ncol = 4)
# Sweep with Complex STATS
data_ex2 <- sweep(x = data, MARGIN = 1,
STATS = c(1, 2, 3, 4, 5, 6),
FUN = "+")
# Print example 2
print(data_ex2)
输出:
[,1] [,2] [,3] [,4]
[1,] 1 1 1 1
[2,] 2 2 2 2
[3,] 3 3 3 3
[4,] 4 4 4 4
[5,] 5 5 5 5
[6,] 6 6 6 6
在上面的示例中,我们使用了 sweep()函数和统计信息。