How to check if a formula is one-sided?

I need to check if the formula is one-way (e.g. ~ a , not a~b ).

Now I am doing something like this:

 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 

Is there a better way? I worry, there are types of formulas that I don’t know about that can elude this test.

+4
source share
1 answer

I would use the terms function and extract the response attribute:

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

Edit

As @Arun points out, terms cannot expand a formula object with a special like . in it, not knowing the data.frame to which the special belongs. A workaround for this would be to include dummy data.frame in the terms formula:

 ## 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 
+6
source

Source: https://habr.com/ru/post/1479153/


All Articles