developer tip

'스위프'기능 사용 방법

copycodes 2020. 8. 27. 07:55
반응형

'스위프'기능 사용 방법


R 패키지의 소스를 보면 sweep꽤 자주 사용되는 함수를 볼 수 있습니다 . 때로는 더 간단한 함수가 충분할 때 (예 :) 사용되며 apply, 다른 경우에는 코드 블록을 단계별로 실행하는 데 상당한 시간을 소비하지 않고는 정확히 무엇을하는지 알 수 없습니다.

sweep더 간단한 함수를 사용하여의 효과를 재현 할 수 있다는 사실은 sweep의 핵심 사용 사례를 이해하지 못함을 시사 하고이 함수가 자주 사용된다는 사실은 매우 유용하다는 것을 시사합니다.

문맥:

sweepR의 표준 라이브러리에있는 함수입니다. 인수는 다음과 같습니다.

sweep(x, MARGIN, STATS, FUN="-", check.margin=T, ...)

# x is the data
# STATS refers to the summary statistics which you wish to 'sweep out'
# FUN is the function used to carry out the sweep, "-" is the default

보시다시피 인수는 하나 이상의 매개 변수가 필요 apply하지만 .sweepSTATS

또 다른 주요 차이점은 입력 배열 과 동일한 모양sweep 의 배열 반환하는 반면에서 반환되는 결과는 전달 된 함수 따라 달라진다는 것입니다.apply

sweep 행동 :

# e.g., use 'sweep' to express a given matrix in terms of distance from 
# the respective column mean

# create some data:
M = matrix( 1:12, ncol=3)

# calculate column-wise mean for M
dx = colMeans(M)

# now 'sweep' that summary statistic from M
sweep(M, 2, dx, FUN="-")

     [,1] [,2] [,3]
[1,] -1.5 -1.5 -1.5
[2,] -0.5 -0.5 -0.5
[3,]  0.5  0.5  0.5
[4,]  1.5  1.5  1.5

요약하자면 제가 찾고있는 것은 sweep.

R 문서, 메일 링리스트 또는 '기본'R 소스를 낭송하거나 링크하지 마십시오. 내가 읽었다 고 가정합니다. 제가 관심있는 것은 경험이 많은 R 프로그래머 / 분석가 sweep가 자신의 코드에서 사용하는 방법 입니다.


sweep()일반적으로 행 또는 열별로 행렬을 연산 할 때 사용되며 연산의 다른 입력은 각 행 / 열에 대해 다른 값입니다. 행 또는 열로 작동하는지 여부는에서와 같이 MARGIN에 의해 ​​정의됩니다 apply(). 내가 "다른 입력"이라고 부르는 것에 사용 된 값은 STATS에 의해 정의됩니다. 따라서 각 행 (또는 열)에 대해 STATS에서 값을 가져와 FUN에서 정의한 작업에 사용합니다.

예를 들어 정의한 행렬의 첫 번째 행에 1, 두 번째 행에 2 등을 추가하려면 다음을 수행합니다.

sweep (M, 1, c(1: 4), "+")

솔직히 R 문서의 정의도 이해하지 못했고, 방금 예제를 찾아 보았습니다.


sweep ()은 아래와 같이 큰 행렬을 열 단위로 또는 행 단위로 체계적으로 조작하는 데 유용 할 수 있습니다.

> print(size)
     Weight Waist Height
[1,]    130    26    140
[2,]    110    24    155
[3,]    118    25    142
[4,]    112    25    175
[5,]    128    26    170

> sweep(size, 2, c(10, 20, 30), "+")
     Weight Waist Height
[1,]    140    46    170
[2,]    120    44    185
[3,]    128    45    172
[4,]    122    45    205
[5,]    138    46    200

Granted, this example is simple, but changing the STATS and FUN argument, other manipulations are possible.


This question is a bit old, but since I've recently faced this problem a typical use of sweep can be found in the source code for the stats function cov.wt, used for computing weighted covariance matrices. I'm looking at the code in R 3.0.1. Here sweep is used to subtract out column means before computing the covariance. On line 19 of the code the centering vector is derived:

 center <- if (center) 
        colSums(wt * x)
    else 0

and on line 54 it is swept out of the matrix

x <- sqrt(wt) * sweep(x, 2, center, check.margin = FALSE)

The author of the code is using the default value FUN = "-", which confused me for a while.


One use is when you're computing weighted sums for an array. Where rowSums or colSums can be assumed to mean 'weights=1', sweep can be used prior to this to give a weighted result. This is particularly useful for arrays with >=3 dimensions.

This comes up e.g. when calculating a weighted covariance matrix as per @James King's example.

Here's another based on a current project:

set.seed(1)
## 2x2x2 array
a1 <- array(as.integer(rnorm(8, 10, 5)), dim=c(2, 2, 2))
## 'element-wise' sum of matrices
## weights = 1
rowSums(a1, dims=2)
## weights
w1 <- c(3, 4)
## a1[, , 1] * 3;  a1[, , 2] * 4
a1 <- sweep(a1, MARGIN=3, STATS=w1, FUN="*")
rowSums(a1, dims=2)

You could use sweep function to scale and center data like the following code. Note that means and sds are arbitrary here (you may have some reference values that you want to standardize data based on them):

df=matrix(sample.int(150, size = 100, replace = FALSE),5,5)

df_means=t(apply(df,2,mean))
df_sds=t(apply(df,2,sd))

df_T=sweep(sweep(df,2,df_means,"-"),2,df_sds,"/")*10+50

This code convert raw scores to T scores (with mean=50 and sd=10):

> df
     [,1] [,2] [,3] [,4] [,5]
[1,]  109    8   89   69   15
[2,]   85   13   25  150   26
[3,]   30   79   48    1  125
[4,]   56   74   23  140  100
[5,]  136  110  112   12   43
> df_T
         [,1]     [,2]     [,3]     [,4]     [,5]
[1,] 56.15561 39.03218 57.46965 49.22319 40.28305
[2,] 50.42946 40.15594 41.31905 60.87539 42.56695
[3,] 37.30704 54.98946 47.12317 39.44109 63.12203
[4,] 43.51037 53.86571 40.81435 59.43685 57.93136
[5,] 62.59752 61.95672 63.27377 41.02349 46.09661

참고URL : https://stackoverflow.com/questions/3444889/how-to-use-the-sweep-function

반응형