R語言中的sweep()函數用於對數據矩陣中的行或列應用“+或-”操作。它用於掃描來自 data-framework 的值。
用法:
sweep(x, MARGIN, STATS, FUN)
參數:
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:掃描矩陣
Python3
# 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)
輸出:
[,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 一起使用
Python3
# 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() 函數和統計信息。
相關用法
- R語言 transform()用法及代碼示例
- R語言 round()用法及代碼示例
- R語言 summarise()用法及代碼示例
- R語言 row()用法及代碼示例
- R語言 max.col()用法及代碼示例
- R語言 colMeans()用法及代碼示例
注:本文由純淨天空篩選整理自akhilsharma870大神的英文原創作品 Changing row and column values of a Matrix in R Language – sweep() function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。