R에서 조건에 맞는 행 추출하는 방법은 엄청 많음.
인덱싱 사용, subset(), filter() 등 여러 가지인 데, 젤 많이 쓰는 건 간단한 filter()이다.
00. 데이터 불러오기
R 내장 데이터셋 중 젤 많이 쓰는 iris 데이터를 사용.
01. 인덱싱을 사용한 추출 : 데이터셋명[조건, ]
iris[iris$Species=='setosa',] # Species가 'setosa'인 행만 추출
iris[iris$Sepal.Length >=5,] # Sepal.Length가 5 이상인 행만 추출
02. subset() 사용
: subset(x=iris, subset=, select= )
subset(iris, Species == "setosa") # Species가 setosa인 행 추출
# Sepal.Length > 7.6 인 행을 뽑고 select옵션을 사용해서 (Petal.Length, Petal.Width) 열만 뽑아옴
subset(iris, Sepal.Length > 7.6, select=c(Petal.Length, Petal.Width))
03. dplyr :: filter() 사용
iris %>% filter(Species == "setosa") # Species가 setosa인 행 추출
iris %>% filter(Species != "setosa") # Species가 setosa가 아닌 행 추출
iris %>% filter(between(Sepal.Length, 4, 6) #Sepal.Length가 4이상 6이하
& Species == 'versicolor') # Species가 versicolor인 행
더보기
참고 서적 / 위키북스|Must Learning with R (개정판)
'R > dplyr' 카테고리의 다른 글
R | dplyr | 샘플 데이터 무작위 추출 - sample_frac(), sample_n() (0) | 2023.01.02 |
---|---|
R | dplyr | mutate, mutate_if , mutate_at - 새로운 변수 생성 및 처리 (1) | 2022.12.28 |
R | dplyr | 변수 추출 select(), select_if() (0) | 2022.12.15 |
R | dplyr | 데이터 정렬(arrange) (0) | 2022.12.09 |
R | dplyr | 집계 데이터 만들기(group by, summarise) (0) | 2022.12.06 |