How to choose a part of a formula in a formula in R?

Suppose I have the following formula:

fr <- formula(y~myfun(x)+z)

frIs this object a function in R that returns myfun(x)? I wrote my own function (code below) that basically does what I need, but maybe there is a standard way to do this?

Code for my function:

selectmds <- function(expr,funcn) {
    if(length(expr)>2) {
        a <- expr[[2]]
        b <- expr[[3]]
        if(length(a)>1) {
            if(as.name(a[[1]])==funcn) {
                if(length(grep(funcn,all.names(b)))>0) {
                    return(list(a,selectmds(b,funcn)))
                }
                else return(list(a))
            }
        }
        if(length(b)>1) {
            if(as.name(b[[1]])==funcn) {
                if(length(grep(funcn,all.names(a)))>0) {
                    return(list(b,selectmds(a,funcn)))
                }
                else return(list(b))
            }
        }
        for(i in 2:length(expr)) {
            if(length(grep(funcn,all.names(expr[[i]])))>0)return(selectmds(expr[[i]],funcn))
        }
    }
    return(NULL)
}

Here are some examples:

> selectmds(formula(y~myfun(x)+z),"myfun")
[[1]]
myfun(x)


> unlist(selectmds(formula(y~myfun(x)+z+myfun(zz)),"myfun"))
[[1]]
myfun(zz)

[[2]]
myfun(x)
+5
source share
2 answers

Not sure if this is the best, but you can do this:

f <- function(fm, fun) {
  l <- as.list(attr(terms(fm), "variables"))[-1]
  l[grep(fun, l)]
}

then

> f(formula(y~myfun(x)+z),"myfun")
[[1]]
myfun(x)

> f(formula(y~myfun(x)+z+myfun(zz)),"myfun")
[[1]]
myfun(x)

[[2]]
myfun(zz)
+7
source

There is an argument specialsfor terms, which allows you to specify named functions in a formula to retrieve by position.

So you can write

selectmds<-function(form,fn) {
  tt<-terms(form,specials=fn);
  idx<-attr(tt,"specials");
  v<-as.list(attr(tt,"variables"))[-1];
  unlist(lapply(idx,function(i) v[i]))
}

Then your test files give

> selectmds(formula(y~myfun(x)+z),"myfun")
$myfun
myfun(x)

> selectmds(formula(y~myfun(x)+z+myfun(zz)),"myfun")
$myfun1
myfun(x)

$myfun2
myfun(zz)

But you can also do

> selectmds(formula(y~myfun(x)+myfun(x2)+z+yourfun(zz)),c("myfun","yourfun"))
$myfun1
myfun(x)

$myfun2
myfun(x2)

$yourfun
yourfun(zz)

Where you can strike unlistso that it is nested using a named function.

+2
source

All Articles