R:动态更新公式 [英] R: Dynamically update formula

查看:62
本文介绍了R:动态更新公式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何动态更新公式?

示例:

myvar <- "x"

update(y ~ 1 + x, ~ . -x)
# y ~ 1 (works as intended)

update(y ~ 1 + x, ~ . -myvar)
# y ~ x (doesn't work as intended)

update(y ~ 1 + x, ~ . -eval(myvar))
# y ~ x (doesn't work as intended)

推荐答案

您可以在 update() 调用中使用 paste().

You can use paste() within the update()call.

myvar <- "x"
update(y ~ 1 + x, paste(" ~ . -", myvar))
# y ~ 1

编辑

正如@A.Fischer 在评论中指出的那样,如果 myvar 是长度 > 的向量,这将不起作用.1

Edit

As @A.Fischer noted in the comments, this won't work if myvar is a vector of length > 1

myvar <- c("k", "l")
update(y ~ 1 + k + l + m, paste(" ~ . -", myvar))
# y ~ l + m
# Warning message:
# Using formula(x) is deprecated when x is a character vector of length > 1.
#   Consider formula(paste(x, collapse = " ")) instead.

只是k"被删除,但是l"保留在公式中.

Just "k" gets removed, but "l" remains in the formula.

在这种情况下,我们可以将公式转换为字符串,添加/删除我们想要更改的内容并使用 reformulate 重建公式,例如:

In this case we could transform the formula into a strings, add/remove what we want to change and rebuild the formula using reformulate, something like:

FUN <- function(fo, x, negate=FALSE) {
  foc <- as.character(fo)
  s <- el(strsplit(foc[3], " + ", fixed=T))
  if (negate) {
    reformulate(s[!s %in% x], foc[2], env=.GlobalEnv)
  } else {
    reformulate(c(s, x), foc[2], env=.GlobalEnv)
  }
}

fo <- y ~ 1 + k + l + m

FUN(fo, c("n", "o"))  ## add variables
# y ~ 1 + k + l + m + n + o
FUN(fo, c("k", "l"), negate=TRUE))  ## remove variables
# y ~ 1 + m

这篇关于R:动态更新公式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆