【问题标题】:how to avoid writing large number of column names when fitting a model in R在 R 中拟合模型时如何避免编写大量列名
【发布时间】:2022-07-06 04:56:32
【问题描述】:

在拟合逻辑回归模型时,我想对数据集的非线性变量使用 bs() 函数。

df <- data.frame(a = c(0,1), b = c(0,1), d = c(0,1), e = c(0,1),
                  f= c("m","f"), output = c(0,1))
 
library(splines) 
model <- glm(output~ bs(a, df=2)+ bs(b, df=2)+ bs(d, df=2)+ bs(e, df=2)+
                      factor(f) ,
                      data = df, 
                      family = "binomial") 

在我的实际数据集中,bs()ed 的列数比这个例子多得多。有没有办法在不写所有条款的情况下做到这一点?

【问题讨论】:

    标签: r logistic-regression bspline


    【解决方案1】:

    我们可以使用一些字符串操作,以及reformulate:

    predictors <- c("a", "b", "d", "e")
    bspl.terms <- sprintf("bs(%s, df = 2)", predictors)
    other.terms <- "factor(f)"
    form <- reformulate(c(bspl.terms, other.terms), response = "output")
    #output ~ bs(a, df = 2) + bs(b, df = 2) + bs(d, df = 2) + bs(e, 
    #    df = 2) + factor(f)
    

    【讨论】:

    • 是的。我打算去一些更高级的东西,比如predictors &lt;- setdiff(names(df)[sapply(df, is.numeric)], "output"),但这很棒。
    猜你喜欢
    • 2019-02-13
    • 2011-05-31
    • 1970-01-01
    • 1970-01-01
    • 2020-12-31
    • 2019-12-15
    • 1970-01-01
    • 2011-02-10
    • 2011-03-29
    相关资源
    最近更新 更多