Statistics, R

R에서 numeric class 변수들만 한 번에 뽑기

Jonggg 2023. 10. 27. 23:53

R에서 데이터 작업을 하다보면 가끔 numeric class 변수들만 뽑고 싶을 때가 있다 (예를들어 numeric 변수들만으로 구성된 데이터로 만들어서 correlation matrix를 빠르게 보고싶다던지..)

먼저 다음과 같이 예시 데이터를 가져와보자.

data(iris)
str(iris)
## 'data.frame':    150 obs. of  5 variables:
##  $ Sepal.Length: num  5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ...
##  $ Sepal.Width : num  3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ...
##  $ Petal.Length: num  1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 ...
##  $ Petal.Width : num  0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2 0.2 0.1 ...
##  $ Species     : Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 1 1 1 1 1 1 ...

str()를 통해 확인해봤을때, Species만 factor고 나머지는 numeric임을 볼 수 있다.

여기서 우리는 아래와 같이 dplyr 패키지의 select_if() 함수를 이용해서 특정 조건의 변수를만으로 뽑을 수 있다 (여기서는 조건에 is.numeric 을 걸었다.)

library(dplyr)
## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
iris %>% select_if(is.numeric) %>% head()
##   Sepal.Length Sepal.Width Petal.Length Petal.Width
## 1          5.1         3.5          1.4         0.2
## 2          4.9         3.0          1.4         0.2
## 3          4.7         3.2          1.3         0.2
## 4          4.6         3.1          1.5         0.2
## 5          5.0         3.6          1.4         0.2
## 6          5.4         3.9          1.7         0.4

아래와 같은 코드를 이용해서도 numeric class 변수들로만 구성된 데이터로 만들 수 있다.

index_col <- sapply(iris, FUN=function(x) is.numeric(x))
iris[,index_col] %>% head()
##   Sepal.Length Sepal.Width Petal.Length Petal.Width
## 1          5.1         3.5          1.4         0.2
## 2          4.9         3.0          1.4         0.2
## 3          4.7         3.2          1.3         0.2
## 4          4.6         3.1          1.5         0.2
## 5          5.0         3.6          1.4         0.2
## 6          5.4         3.9          1.7         0.4

여러가지 상황에서 apply 함수 패밀리의 일반적인 활용 능력을 키우고, 다른 상황에서도 적절히 응용하기 위해서, 후자의 방법으로 코드 작성 습관을 들이길 개인적으로 추천한다.