R에서 비율을 계산하는 방법(예제 포함)


다음 방법을 사용하여 R의 두 열 값 간의 비율을 계산할 수 있습니다.

방법 1: 기본 R 사용

 #calculate ratio between variable1 and variable2
df$ratio <- df$variable1/df$variable1

#calculate ratio between variable1 and variable2, rounded to 2 decimal places
df$ratio <- round(df$variable1/df$variable2, 2 )

방법 2: dplyr 사용

 library (dplyr)

#calculate ratio between variable1 and variable2
df <- df %>%
        mutate(ratio = variable1/variable2)

#calculate ratio between variable1 and variable2, rounded to 2 decimal places
df <- df %>%
        mutate(ratio = round(variable1/variable2, 2 ))

이 튜토리얼에서는 다양한 농구 선수가 촬영하고 시도한 총 슛 수를 보여주는 다음 데이터 프레임을 사용하여 실제로 각 방법을 사용하는 방법을 설명합니다.

 #create data frame
df <- data. frame (players=c('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'),
                 makes=c(4, 4, 3, 6, 7, 8, 3, 10),
                 attempts=c(12, 7, 5, 6, 10, 12, 5, 19))

#view data frame
df

  players makes attempts
1 to 4 12
2 B 4 7
3 C 3 5
4 D 6 6
5 E 7 10
6 F 8 12
7 G 3 5
8:10:19 a.m.

예 1: R 기준을 사용하여 비율 계산

다음 코드는 R 베이스를 사용하여 마크시도 열의 값 사이의 비율을 계산하는 방법을 보여줍니다.

 #calculate ratio between makes and attempts columns
df$ratio <- df$makes/df$attempts

#view updated data frame
df

  players makes attempts ratio
1 A 4 12 0.3333333
2 B 4 7 0.5714286
3 C 3 5 0.6000000
4 D 6 6 1.0000000
5 E 7 10 0.7000000
6 F 8 12 0.6666667
7 G 3 5 0.6000000
8:10:19 AM 0.5263158

첫 번째 플레이어의 시도 시도 비율은 4/12 = 0.33 입니다.

즉, 첫 번째 선수가 슛 시도의 약 33% 를 성공했다는 것입니다.

다른 모든 플레이어의 비율 값도 같은 방식으로 해석할 수 있습니다.

round() 함수를 사용하여 비율 값을 특정 소수 자릿수로 반올림할 수도 있습니다.

 #calculate ratio between makes and attempts columns, rounded to 2 decimal places
df$ratio <- round(df$makes/df$attempts, 2 )

#view updated data frame
df

  players makes attempts ratio
1 to 4 12 0.33
2 B 4 7 0.57
3 C 3 5 0.60
4 D 6 6 1.00
5 E 7 10 0.70
6 F 8 12 0.67
7 G 3 5 0.60
8:10:19 0.53

이제 비율 열의 각 값이 소수점 이하 두 자리로 반올림되었습니다.

예 2: dplyr을 사용하여 비율 계산

다음 코드는 dplyr 패키지를 사용하여 마크시도 열의 값 사이의 비율을 계산하는 방법을 보여줍니다.

 library (dplyr)

#add new column that shows ratio of makes to attempts
df <- df %>%
        mutate(ratio = makes/attempts)

#view updated data frame
df

  players makes attempts ratio
1 A 4 12 0.3333333
2 B 4 7 0.5714286
3 C 3 5 0.6000000
4 D 6 6 1.0000000
5 E 7 10 0.7000000
6 F 8 12 0.6666667
7 G 3 5 0.6000000
8:10:19 AM 0.5263158

round() 함수를 사용하여 비율 값을 특정 소수 자릿수로 반올림할 수도 있습니다.

 library (dplyr)

#add new column that shows ratio of makes to attempts, rounded to 2 decimal places
df <- df %>%
        mutate(ratio = round(makes/attempts, 2 ))

#view updated data frame
df

  players makes attempts ratio
1 to 4 12 0.33
2 B 4 7 0.57
3 C 3 5 0.60
4 D 6 6 1.00
5 E 7 10 0.70
6 F 8 12 0.67
7 G 3 5 0.60
8:10:19 0.53

이제 비율 열의 각 값이 소수점 이하 두 자리로 반올림되었습니다.

기본 R 방법과 dplyr 방법은 동일한 결과를 생성합니다.

추가 리소스

다음 튜토리얼에서는 R에서 다른 일반적인 작업을 수행하는 방법을 설명합니다.

dplyr을 사용하여 고유 값을 필터링하는 방법
dplyr을 사용하여 여러 조건으로 필터링하는 방법
R의 열에서 발생 횟수를 계산하는 방법

의견을 추가하다

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다