如何测试公式是否是片面的?

Ari*_*man 4 r

我需要测试一个公式是否是片面的(例如,~ a而不是a~b).

现在我正在做这样的事情:

test <- list( ~ a + b, a ~ b + c, b + c ~ a )
isOneSided <- function(form) length(form)==2 && sum(grepl("~",form))==1
> sapply(test,isOneSided)
[1]  TRUE FALSE FALSE
Run Code Online (Sandbox Code Playgroud)

有没有更好的办法?我担心有些类型的公式我不知道可以逃避这个测试.

Sim*_*lon 6

我会使用该terms函数并提取响应属性:

test <- list( ~ a + b, a ~ b + c, b + c ~ a )
sapply( test , function(x) attr( terms(x) , "response" ) == 0 )
# [1]  TRUE FALSE FALSE
Run Code Online (Sandbox Code Playgroud)

编辑

正如@Arun指出的terms那样,.在不知道data.frame特殊引用的情况下,无法扩展具有特殊功能的公式对象.解决方法是data.frameterms函数调用中包含一个虚拟:

## If we want to expand the '.' in b + c ~ .    
test <- list( ~ a + b, a ~ b + c, b + c ~ a ,  b + c ~ . , . ~ b + c  )
sapply( test , function(x) attr( terms(x , data = data.frame(runif(1))) , "response" ) == 0 )
# [1]  TRUE FALSE FALSE FALSE FALSE
Run Code Online (Sandbox Code Playgroud)