gpt4 book ai didi

r - 创建表达式测试,看看 R 中的 `as.formula(' X ~ 1')` 是否包含截距?

转载 作者:行者123 更新时间:2023-12-01 08:22:44 26 4
gpt4 key购买 nike

在 R 中,可以指定一个公式:

F <- as.formula('X ~ 1')

我正在尝试想出一种方法来测试上面的 F 是否仅包含截取,即 ~1。我试图使用 grepl 无济于事。有没有办法确定上面的公式是否只包含一个截距?即,我希望提出一种在以下不同情况下返回 true 的方法:

F <- as.formula('X~ 1')
F <- as.formula('X~1')
F <- as.formula('X ~1')

也是。谢谢!

最佳答案

attr(terms(x~y), 'intercept') 会做你想做的事。

formula <- x~y
formula2 <- x~y-1 # no intercept
attr(terms(formula), 'intercept')
## [1] 1
attr(terms(formula2), 'intercept')
## [1] 0

编辑:我最初误读了这个问题。如果您正在寻找一个特定示例来查找公式是否仅包含您可以使用的截距:

f1 <- x ~ y
f2 <- x ~ y-1
f3 <- x ~ 1
f3 <- x ~ 0

onlyIntercept <- function(f){
return(attr(terms(f), 'intercept') & length(attr(terms(f), 'factors')) == 0)
}
# Examples on above, then on OPs examples:
onlyIntercept(f1)
## [1] FALSE
onlyIntercept(f2)
## [1] FALSE
onlyIntercept(f3)
## [1] TRUE
onlyIntercept(f4)
## [1] FALSE

onlyIntercept(as.formula('X~ 1'))
## [1] TRUE
onlyIntercept(as.formula('X~1'))
## [1] TRUE
onlyIntercept(as.formula('X ~1'))
## [1] TRUE

我在此处定义的 onlyIntercept 函数检查拦截属性是 0 还是 1,并检查是否有任何其他因素(变量)通常会包含在模型中。如果不存在,则此属性的长度为 0,可以轻松检查。

关于r - 创建表达式测试,看看 R 中的 `as.formula(' X ~ 1')` 是否包含截距?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50073814/

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