从字符串创建公式调用

编程入门 行业动态 更新时间:2024-10-26 19:27:21
本文介绍了从字符串创建公式调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我使用最佳子集选择包来确定用于构建模型的最佳独立变量(我确实有这样做的特定原因,而不是直接使用最佳子集对象).我想以编程方式提取特征名称,并使用生成的字符串构建我的模型公式.结果将是这样的:

I use a best subset selection package to determine the best independent variables from which to build my model (I do have a specific reason for doing this instead of using the best subset object directly). I want to programmatically extract the feature names and use the resulting string to build my model formula. The result would be something like this:

x <- "x1 + x2 + x3" y <- "Surv(time, event)"

因为我正在构建 coxph 模型,所以公式如下:

Because I'm building a coxph model, the formula is as follows:

coxph(Surv(time, event) ~ x1 + x2 + x3)

使用这些字符串字段,我试图像这样构造公式:

Using these string fields, I tried to construct the formula like so:

form <- y ~ x

这会创建一个 formula 类的对象,但是当我调用 coxph 时,它不会基于从公式对象创建的引用进行评估.我收到以下错误:

This creates an object of class formula but when I call coxph it doesn't evaluate based on the references created form the formula object. I get the following error:

Error in model.frame.default(formula = y ~ x) : object is not a matrix

如果我对 coxph 调用中的对象y和x调用 eval ,则会得到以下信息:

If I call eval on the objects y and x within the coxph call, I get the following:

Error in model.frame.default(formula = eval(y) ~ eval(x), data = df) :

可变长度不同(为'eval(x)'找到)

variable lengths differ (found for 'eval(x)')

我不太确定该如何进行.感谢您的输入.

I'm not really sure how to proceed. Thanks for your input.

推荐答案

找不到好的重复对象,因此请发表评论作为答案.

Couldn't find a good dupe, so posting comment as an answer.

如果将完整的公式构建为字符串,包括〜,则可以在其上使用 as.formula ,例如

If you build the full formula as a string, including the ~, you can use as.formula on it, e.g.,

x = "x1 + x2 + x3" y = "Surv(time, event)" form = as.formula(paste(y, "~", x)) coxph(form, data = your_data)

有关可重现的示例,请考虑?coxph 帮助页面底部的第一个示例:

For a reproducible example, consider the first example at the bottom of the ?coxph help page:

library(survival) test1 <- list(time=c(4,3,1,1,2,2,3), status=c(1,1,1,0,1,1,0), x=c(0,2,1,1,1,0,0), sex=c(0,0,0,0,1,1,1)) # Fit a stratified model coxph(Surv(time, status) ~ x + strata(sex), test1) # Call: # coxph(formula = Surv(time, status) ~ x + strata(sex), data = test1) # # coef exp(coef) se(coef) z p # x 0.802 2.231 0.822 0.98 0.33 # # Likelihood ratio test=1.09 on 1 df, p=0.3 # n= 7, number of events= 5 lhs = "Surv(time, status)" rhs = "x + strata(sex)" form = as.formula(paste(lhs, "~", rhs)) form # Surv(time, status) ~ x + strata(sex) ## formula looks good coxph(form, test1) # Call: # coxph(formula = form, data = test1) # # coef exp(coef) se(coef) z p # x 0.802 2.231 0.822 0.98 0.33

两种方法的结果相同.

更多推荐

从字符串创建公式调用

本文发布于:2023-10-28 02:06:29,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1535186.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   公式

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!