R에서 which 함수를 사용하는 방법(예제 포함)


R의 which() 함수는 논리 벡터에서 TRUE 인 요소의 위치를 반환합니다.

이 튜토리얼에서는 이 기능의 실제 사용에 대한 몇 가지 예를 제공합니다.

예 1: 벡터에서 요소 찾기

다음 코드는 5와 같은 벡터의 모든 요소 위치를 찾는 방법을 보여줍니다.

 #create data
data <- c(1, 2, 2, 3, 4, 4, 4, 5, 5, 12)

#find the position of all elements equal to 5
which (data == 5)

[1] 8 9

벡터에서 위치 89 의 요소는 값 5와 동일하다는 것을 알 수 있습니다.

또한 5가 아닌 벡터의 모든 요소의 위치를 찾을 수도 있습니다.

 #find the position of all elements not equal to 5
which (data != 5)

[1] 1 2 3 4 5 6 7 10

또한 두 값 사이에 있거나 두 값 외부에 있는 요소를 찾을 수도 있습니다.

 #find the position of all elements with values between 2 and 4
which (data >= 2 & data <= 4)

[1] 2 3 4 5 6 7

#find the position of all elements with values outside of 2 and 4
which (data < 2 | data > 4)

[1] 1 8 9 10

예제 2: 벡터에서 발생 횟수 계산

다음 코드는 length() 함수를 사용하여 특정 값보다 큰 벡터의 요소 수를 찾는 방법을 보여줍니다.

 #createdata
data <- c(1, 2, 2, 3, 4, 4, 4, 5, 5, 12)

#find number of elements greater than 4
length ( which (data > 4))

[1] 3

이 벡터에는 4보다 큰 값을 갖는 3개의 요소가 있음을 알 수 있습니다.

예 3: 데이터 프레임에서 행 찾기

다음 코드는 특정 열의 최대값 또는 최소값을 포함하는 데이터 프레임의 행을 반환하는 방법을 보여줍니다.

 #create data frame
df <- data. frame (x = c(1, 2, 2, 3, 4, 5),
                 y = c(7, 7, 8, 9, 9, 9),
                 z = c('A', 'B', 'C', 'D', 'E', 'F'))

#view data frame
df

  X Y Z
1 1 7 A
2 2 7 B
3 2 8 C
4 3 9 D
5 4 9 E
6 5 9 F

#return row that contains the max value in column x
df[ which . max (df$x), ]

  X Y Z
6 5 9 F

#return row that contains the min value in column x
df[ which . min (df$x), ]

  X Y Z
1 1 7 A

예제 4: 데이터 프레임의 행별 하위 집합

다음 코드는 데이터 프레임을 특정 기준을 충족하는 행으로 세분화하는 방법을 보여줍니다.

 #create data frame
df <- data. frame (x = c(1, 2, 2, 3, 4, 5),
                 y = c(7, 7, 8, 9, 9, 9),
                 z = c('A', 'B', 'C', 'D', 'E', 'F'))

#view data frame
df

  X Y Z
1 1 7 A
2 2 7 B
3 2 8 C
4 3 9 D
5 4 9 E
6 5 9 F

#return subset of data frame where values in column y are greater than 8
df[ which (df$y > 8), ]

  X Y Z
4 3 9 D
5 4 9 E
6 5 9 F

이 페이지 에서 더 많은 R 튜토리얼을 찾아보세요.

의견을 추가하다

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