本文介绍了R更新功能,如何删除与预定变量相关的所有变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个R公式对象:

 formula1 <- y ~ x1 + x2 + x3 + x1:x2

我想通过删除所有与x1相关的变量来更新此公式对象.那就是x1和x1:x2.

I want to update this formula object by dropping all x1-related variables. That is x1 AND x1:x2.

如果我使用更新功能,

 update(formula1,.~.-x1)

我得到:

 y ~ x2 + x3 + x1:x2

这不是我想要的.在实践中,我不知道在Formula1对象中定义了多少个x1交互作用.

This is not what I want. In practice, I do not know how many interaction effects of x1 are defined in the formula1 object.

是否有获取

 y ~ x2 + x3

推荐答案

以下是删除包含所有存在该术语的所有相互作用的术语的功能:

Here's a function to remove a term including all interactions in which the term is present:

remove_terms <- function(form, term) {
  fterms <- terms(form)
  fac <- attr(fterms, "factors")
  idx <- which(as.logical(fac[term, ]))
  new_fterms <- drop.terms(fterms, dropx = idx, keep.response = TRUE)
  return(formula(new_fterms))
}

应用功能

formula1 <- y ~ x1 + x2 + x3 + x1:x2

# the term that should be removed
to_remove <- "x1"

remove_terms(formula1, to_remove)
# y ~ x2 + x3

这篇关于R更新功能,如何删除与预定变量相关的所有变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-26 19:16