[R] R에서 Linux명령어를 실행하는 system()과 system2()의 차이
작성 : 2023.05.07.일
| system( )이란?
Dada2의 ITS tutorial 중 리눅스에 설치된 R에서 Linux의 명령어를 실행하는 system2() 함수가 등장한다.
아래 코드는 Linux에 설치된 R에서 for 함수를 사용해 Cutadapt를 실행하는 그 예시이다.
cutadapt <- "/Users/nbetrap/miniconda2/bin/cutadapt" # 설치된 cutadapt의 경로로, 본인의 컴퓨터에 맞게 수정해야 한다.
system2(cutadapt, args = "--version") # Run shell commands from R
path.cut <- file.path(path, "cutadapt")
if(!dir.exists(path.cut)) dir.create(path.cut)
fnFs.cut <- file.path(path.cut, basename(fnFs))
fnRs.cut <- file.path(path.cut, basename(fnRs))
FWD.RC <- dada2:::rc(FWD)
REV.RC <- dada2:::rc(REV)
# Trim FWD and the reverse-complement of REV off of R1 (forward reads)
R1.flags <- paste("-g", FWD, "-a", REV.RC)
# Trim REV and the reverse-complement of FWD off of R2 (reverse reads)
R2.flags <- paste("-G", REV, "-A", FWD.RC)
# Run Cutadapt
for(i in seq_along(fnFs)) {
system2(cutadapt, args = c(R1.flags, R2.flags, "-n", 2, # -n 2 required to remove FWD and REV from reads
"-o", fnFs.cut[i], "-p", fnRs.cut[i], # output files
fnFs.filtN[i], fnRs.filtN[i])) # input files
}
2가 있다는 것은 1도 있다는 뜻이다. 일단 system() 함수의 예시는 아래와 같다.
system("echo 'hello world!' > test.txt")
이 함수는 Linux상에서 "echo 'hello world!' > test.txt"와 동일하다.
하지만 아래 스크립트는 실행되지 않는다.
system2("echo 'hello world!' > test.txt")
# sh: echo 'hello world!' > test.txt: command not found
# Warning: error in running command
system2() 함수는 system() 함수와 비슷하지만, 좀 더 다른 옵션들이 추가된다. system2() 함수는 실행할 명령어와 명령어의 인자(argument)를 따로 지정해 준다. 위의 "echo 'hello world!' > test.txt"함수를 system2()로 실행시키면 아래와 같다.
system2("bash", args = "-c 'echo \"hello world!\" > test.txt'")
| 이 함수를 효율적으로 사용하기
마이크로바이옴 분석 단계에서 만약에 qiime과 R을 동시에 사용한다면, qiime으로는 기존의 fastq 파일에서 otu table과 taxonomy table을 만들고, R에서는 그 데이터를 이용해 시각화를 할 것이다.
그렇다면 우리는 qiime을 쓰기 위해 Linux로 접속하고, 다시 결과물을 R로 옮겨야 한다.
하지만 Linux상에서 R의 system명령어로 qiime을 실행하고, 이 결과를 phyloseq으로 만드는 전 과정을 자동화할 수 있다.
만약 아래와 같은 qiime분석 단계를 R로 적으면 다음과 같다.
qiime demux summarize \
--i-data demux.qza \
--o-visualization demux.qzv
이 단계를 R에서 system2를 사용하면 아래와 같이 쓸 수 있다.
# qiime 명령어와 인자 정의
qiime_cmd <- "qiime"
qiime_args <- "demux summarize"
input_arg <- "--i-data demux.qza"
output_arg <- "--o-visualization demux.qzv"
# system2 함수를 사용하여 qiime 명령어 실행
system2(command = qiime_cmd,
args = c(qiime_args, input_arg, output_arg),
stdout = TRUE,
stderr = TRUE)
이후 qiime2R 패키지를 통해 phyloseq개체로 만들어 qiime2의 결과물을 바로바로 시각화할 수 있다.
다음엔 이걸로 cutadapt관련 스크립트를 자동화해봐야겠다!
| 참고
- https://irudnyts.github.io/bringing-together-r-and-shell/