gpt4 book ai didi

python - 通过 rpy2 使用 model.matrix?

转载 作者:太空狗 更新时间:2023-10-30 03:00:44 25 4
gpt4 key购买 nike

在我的工作中,我更喜欢 python 而不是 R。有时,我需要使用 R函数,为此我开始尝试 Rpy2。

我试过但未能找到如何使用 Rpy2 复制以下内容

design <- model.matrix(~Subject+Treat)

我已经做到了这一点:

import rpy2.robjects as robjects
fmla = robjects.Formula('~subject+treatment')
env = fmla.environment
env['subject'] = sbj_group
env['treatment'] = trt_group

据我所见here .但是我找不到如何执行 model.matrix。我尝试了几种不同的方法:

robjects.r.model_matrix(fmla)
robjects.r('model.matrix(%s)' %fmla.r_repr())

如您所见,没有一个是正确的。

我是 Rpy2 的新手,在 R 方面相当缺乏经验。任何帮助将不胜感激!

最佳答案

你可以 evaluate strings as R code :

import numpy as np
import rpy2.robjects as ro
import rpy2.robjects.numpy2ri
ro.numpy2ri.activate()
R = ro.r

subject = np.repeat([1,2,3], 4)
treatment = np.tile([1,2,3,4], 3)
R.assign('subject', subject)
R.assign('treatment', treatment)
R('subject <- as.factor(subject)')
R('treatment <- as.factor(treatment)')
R('design <- model.matrix(~subject+treatment)')
R('print(design)')

产量

   (Intercept) subject2 subject3 treatment2 treatment3 treatment4
1 1 0 0 0 0 0
2 1 0 0 1 0 0
3 1 0 0 0 1 0
4 1 0 0 0 0 1
5 1 1 0 0 0 0
6 1 1 0 1 0 0
7 1 1 0 0 1 0
8 1 1 0 0 0 1
9 1 0 1 0 0 0
10 1 0 1 1 0 0
11 1 0 1 0 1 0
12 1 0 1 0 0 1
attr(,"assign")
[1] 0 1 1 2 2 2
attr(,"contrasts")
attr(,"contrasts")$subject
[1] "contr.treatment"

attr(,"contrasts")$treatment
[1] "contr.treatment"

R(...) 返回您可以在 Python 端操作的对象。例如,

design = R('model.matrix(~subject+treatment)')

rpy2.robjects.vectors.Matrix 分配给 design

arr = np.array(design)

使 arr 成为 NumPy 数组

[[ 1.  0.  0.  0.  0.  0.]
[ 1. 0. 0. 1. 0. 0.]
[ 1. 0. 0. 0. 1. 0.]
[ 1. 0. 0. 0. 0. 1.]
[ 1. 1. 0. 0. 0. 0.]
[ 1. 1. 0. 1. 0. 0.]
[ 1. 1. 0. 0. 1. 0.]
[ 1. 1. 0. 0. 0. 1.]
[ 1. 0. 1. 0. 0. 0.]
[ 1. 0. 1. 1. 0. 0.]
[ 1. 0. 1. 0. 1. 0.]
[ 1. 0. 1. 0. 0. 1.]]

列名可以通过

访问
np.array(design.colnames)
# array(['(Intercept)', 'subject2', 'subject3', 'treatment2', 'treatment3',
# 'treatment4'],
# dtype='|S11')

关于python - 通过 rpy2 使用 model.matrix?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28290245/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com