首页 > 解决方案 > 如何在 R 中跨组比较 nls 参数

问题描述

我有一个这样的数据集

IU 样本 观测值
1.5625 s 0.312
1.5625 s 0.302
3.125 s 0.335
3.125 s 0.333
6.25 s 0.423
6.25 s 0.391
12.5 s 0.562
12.5 s 0.56
25 s 0.84
25 s 0.843
50 s 1.202
50 s 1.185
100 s 1.408
100 s 1.338
200 s 1.42
200 s 1.37
1.5625 0.317
1.5625 0.313
3.125 0.345
3.125 0.343
6.25 0.413
6.25 0.404
12.5 0.577
12.5 0.557
25 0.863
25 0.862
50 1.22
50 1.197
100 1.395
100 1.364
200 1.425
200 1.415

我想使用 R 在下面重新创建 SAS 代码。我相信这个 SAS 代码意味着对每个子集执行非线性拟合,其中三个参数相同,一个参数不同。

proc nlin data=assay;
 model obs=D+(A-D)/(1+(iu/((cs∗(sample=“S”)
+Ct∗(sample=“T”))))∗∗(B));
 parms D=1 B=1 Cs=1 Ct=1 A=1;
run;

所以我写了这样的东西然后得到

nlm_1 <- nls(obs ~ (a - d) / (1 + (iu / c[sample]) ^ b) + d, data = csf_1, start = list(a = 0.3, b = 1.8, c = c(25, 25), d = 1.4))
Error in numericDeriv(form[[3L]], names(ind), env) :
Missing value or an infinity produced when evaluating the model

但没有[sample], 模型可以计算

nlm_1 <- nls(obs ~ (a - d) / (1 + (iu / c) ^ b) + d, data = csf_1, start = list(a = 0.3, b = 1.8, c = c(25), d = 1.4))
summary(nlm_1)
Formula: obs ~ (a - d)/(1 + (iu/c)^b) + d

Parameters:
  Estimate Std. Error t value Pr(>|t|)
a  0.31590    0.00824   38.34   <2e-16 ***
b  1.83368    0.06962   26.34   <2e-16 ***
c 25.58422    0.55494   46.10   <2e-16 ***
d  1.44777    0.01171  123.63   <2e-16 ***
---
Signif. codes:
0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.02049 on 28 degrees of freedom

Number of iterations to convergence: 4
Achieved convergence tolerance: 6.721e-06

我不明白,有人能告诉我我的代码有什么问题吗,我怎样才能用 R 实现我的目标?谢谢!

标签: r

解决方案


感谢@akrun。在我转换csf_1$sample为因子后,我终于得到了我想要的。

csf_1[, 2] <- as.factor(c(rep("s", 16), rep("t", 16)))
nlm_1 <- nls(obs ~ (a - d) / (1 + (iu / c[sample]) ^ b) + d, data = csf_1, start = list(a = 0.3, b = 1.8, c = c(25, 25), d = 1.4))
summary(nlm_1)
Formula: obs ~ (a - d)/(1 + (iu/c[sample])^b) + d

Parameters:
    Estimate Std. Error t value Pr(>|t|)
a   0.315874   0.008102   38.99   <2e-16 ***
b   1.833303   0.068432   26.79   <2e-16 ***
c1 26.075317   0.656779   39.70   <2e-16 ***
c2 25.114050   0.632787   39.69   <2e-16 ***
d   1.447901   0.011518  125.71   <2e-16 ***
---
Signif. codes:
0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.02015 on 27 degrees of freedom

Number of iterations to convergence: 4
Achieved convergence tolerance: 6.225e-06

推荐阅读