2024-11-18

Learn R - Compute group means

Here are six boxes filled with either potatos or apples. 

Dataframe df has a group column that indicates whether it's a potato or apple box and a weight colmn that contains the weight of the box.

> df <- data.frame(
+   group=c('potato', 'potato', 'apple', 'apple', 'potato', 'apple'),
+   weight=c(10, 2, 5, 26, 3, 6))

It looks like this.

> df
   group weight
1 potato     10
2 potato      2
3  apple      5
4  apple     26
5 potato      3
6  apple      6

What can we do to get the average weights for the potato and apple boxes, respectively?

First, let's load dplyr.

> library(dplyr)

Then, with df,

  1. group by them with apple/potato group column
  2. send the output via piping (%>%)
  3. summarize the mean of weight and save them with a new column mean.weight.

 df %>% group_by(group) %>% summarize(mean.weight = mean(weight))

# A tibble: 2 × 2
  group  mean.weight
  <chr>        <dbl>
1 apple         12.3
2 potato         5  

The avarage weight for apple boxes is 12.3, and the average weight for potato boxes is 5.

It's that simple! Enjoy coding in R!


R에서 그룹 별로 평균 구하기

여섯 개의 상자 안에 감자 또는 사과가 들어 있다고 합니다. 

데이타프레임 df에는 group에는 감자인지 사과인지가, weight에는 각 상자의 무게가 들어갑니다.

> df <- data.frame(
+   group=c('potato', 'potato', 'apple', 'apple', 'potato', 'apple'),
+   weight=c(10, 2, 5, 26, 3, 6))

이 데이타프레임은 다음과 같습니다.

> df
   group weight
1 potato     10
2 potato      2
3  apple      5
4  apple     26
5 potato      3
6  apple      6

감자 상자, 사과 상자 그룹의 각각의 평균 무게를 구하고 싶다면?

우선 dplyr를 로딩합니다.

> library(dplyr)

df를 가지고

  1. 사과/감자 group 별로 grouping을 해주고 (group_by)
  2. 그 결과를 파이프로 받아서 (%>%)
  3. weight의 평균을 낸 다음에 이를 새로운 컬럼 mean.weight에 넣어줍니다 (summarize).

 > df %>% group_by(group) %>% summarize(mean.weight = mean(weight))

# A tibble: 2 × 2
  group  mean.weight
  <chr>        <dbl>
1 apple         12.3
2 potato         5  

사과상자의 평균 무게는 12.3, 감자상자의 평균은 5임을 알 수 있습니다.

참 쉽죠?