▶ 자연과학/▷ Python
【Python】 파이썬에서 R 실행하기
초록E
2024. 4. 30. 13:19
파이썬에서 R 실행하기 (rpy2 이용)
추천글 : 【Python】 파이썬 목차
1. 개요 [본문]
a. R에서 파이썬 실행하기
1. 개요 [목차]
⑴ 파이썬에서 xCell 실행하기
import scanpy as sc
import pandas as pd
import rpy2.robjects as ro
from rpy2.robjects import pandas2ri
from rpy2.robjects.conversion import localconverter
adata = sc.read_visium('./GSE206552_RAW/GSM6256810_meta1')
dat = adata.X.toarray().T
dat = pd.DataFrame(dat, index=adata.var.index, columns=adata.obs.index)
dat = dat.groupby(dat.index).mean()
genes = dat.index
# Convert the Pandas DataFrame to an R DataFrame using rpy2
with localconverter(ro.default_converter + pandas2ri.converter):
r_dat = ro.conversion.py2rpy(dat)
r_genes = ro.conversion.py2rpy(genes)
# Execute R code
ro.r('''
library(xCell)
my_xCellAnalysis <- function(dat, genes) {
rownames(dat) = genes
dat.xcell = xCellAnalysis(dat, rnaseq = TRUE)#, parallel.sz = 16)
dat.xcell_ = as.data.frame(t(dat.xcell))
colnames(dat.xcell_) = make.names(colnames(dat.xcell_))
return(dat.xcell_)
}
''')
r_dat_xcell_ = ro.r.my_xCellAnalysis(r_dat, r_genes)
# Convert the result back to a pandas DataFrame
with localconverter(ro.default_converter + pandas2ri.converter):
df_result = ro.conversion.rpy2py(r_dat_xcell_)
adata.obs = adata.obs.join(df_result)
sc.pl.spatial(adata, color = df_result.columns[1])
입력: 2024.04.30 13:12