当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


R语言 sweep()用法及代码示例


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() 函数和统计信息。




相关用法


注:本文由纯净天空筛选整理自akhilsharma870大神的英文原创作品 Changing row and column values of a Matrix in R Language – sweep() function。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。