# 🚨 문제
for문으로 수동으로 돌리면 되는데 function안에서 subset_samples쓰면 오류 발생
phy_sub <- subset_sample(ps, Group %in% reference_group)
phy_sub <- subset_sample(ps, Group %in% reference_group)
# h(simpleError(msg, call))에서 다음과 같은 에러가 발생했습니다: 함수 '%in%'를 위한 메소드 선택시 인수 'table'를 평가하는데 오류가 발생했습니다: 객체 'refence_group'를 찾을 수 없습니다
# 문제 원인
함수 내부에서는 비표준평가(NSE)가 실행되는데, 이때 함수 내부에서 다시 지정해 주지 않으면 전역변수에서 변수를 검색하게 된다. 그래서 찾지 못한다.
# 해결 방식
grp <- as.character(sample_data(ps)$Group)
keep_samples <- sample_names(ps)[grp %in% c(refence_group)]
prune_samples(keep_samples, ps)
# 안전한 코드 작성하기
1. 패키지 명시
filter() # ❌ stats::filter()가 호출될 수 있음
dplyr::filter() # ✅ 명시적, 안전
2. rlang 패키지를 사용해 SE 방식으로 코드 작성
- e.g. !!rlang::sym(변수) 로 받기 (나는 주로 이 방식을 사용한다)
my_summary <- function(df, var){
var <- rlang::sym(var)
df %>% dplyr::summarise(mean = mean(!!var, na.rm = TRUE))
}
my_summary(mtcars, "mpg")
3. map 함수 사용시 lambda 보다는 명시적 함수 권장
map(site_list, function(site) {
ps <- phylo_list[[site]]
group_vec <- sample_data(ps)$Group2
keep <- sample_names(ps)[group_vec %in% c("4", "5")]
prune_samples(keep, ps)
})
4. 모든 코드 사용에서 기본형 검사 (방어코드)추가
항상 if (!colname %in% colnames(...)) 방어 코드 추가
# 참고
- https://github.com/joey711/phyloseq/issues/1522
Error while using `subset_samples()` in a user function · Issue #1522 · joey711/phyloseq
Hey, While using the phyloseq package, I came across this issue, I hope you can help me. For my analysis, its important that I am able to filter using functions. I try to filter a phyloseq object w...
github.com
- https://adv-r.hadley.nz/quasiquotation.html#unquoting
19 Quasiquotation | Advanced R
19.1 Introduction Now that you understand the tree structure of R code, it’s time to return to one of the fundamental ideas that make expr() and ast() work: quotation. In tidy evaluation, all...
adv-r.hadley.nz
저같은 사파 출신은 이런 사소한 에러에 눈물이 납니다.
날린 시간이 너무 아깝다😭..
이렇게 마교가 되어버린 나
이번 방학은 advancedR 을 끝내보자 (젭알)