R 통계/R 기초

[R기초] 테이블의 합을 구하는 함수 addmargins()

2021. 9. 23. 21:57
728x90

addmargins() 함수는 데이터 테이블 내에서 열, 행, 행&열의 합산 값을 구해주는 함수이다.

 

addmargins(데이터명 , margin = 숫자)  <숫자: 1 = 열 단위 합산, 2 = 행 단위 합산>

다음의 예시로 하나씩 알아보자

 

임의의 데이터 셋을 만들어 보았다.

#임의 데이터 생성
math <- c(70, 80, 50, 69, 90)
eng <- c(80, 75, 94, 79, 70)
kor <- c(66, 88, 81, 72, 92)

test_score <- cbind(math, eng, kor)

row.names(test_score) <- c("student_A","student_B","student_C","student_D","student_E")

test_score

<결과>
          math eng kor
student_A   70  80  66
student_B   80  75  88
student_C   50  94  81
student_D   69  79  72
student_E   90  70  92

 

1. addmargins(데이터명, margin  = 1): 열 단위 합산 값 출력

with_margin_1 <- addmargins(test_score, margin = 1)
with_margin_1

<결과>
          math eng kor
student_A   70  80  66
student_B   80  75  88
student_C   50  94  81
student_D   69  79  72
student_E   90  70  92
Sum        359 398 399

 

2. addmargins(데이터명, margin  = 2): 행 단위 합산 값 출력

with_margin_2 <- addmargins(test_score, margin = 2)
with_margin_2

<결과>
          math eng kor Sum
student_A   70  80  66 216
student_B   80  75  88 243
student_C   50  94  81 225
student_D   69  79  72 220
student_E   90  70  92 252

 

3. addmargins(데이터명, margin  = c(1,2)): 열&행 단위 합산 값 출력

with_margin_3 <- addmargins(test_score, margin = c(1,2))
with_margin_3

<결과>
          math eng kor  Sum
student_A   70  80  66  216
student_B   80  75  88  243
student_C   50  94  81  225
student_D   69  79  72  220
student_E   90  70  92  252
Sum        359 398 399 1156
728x90