1

我有一个相当具体的正则表达式问题,这让我有些悲伤。我已从混合模型(或lmelme4)中删除了一个或多个固定效应,并希望删除相应的随机斜率。但是,根据随机结构,这可能会留下不必要的+符号,或者更糟糕的是,在|.

分别使用 和 获取lme随机效应公式列表:lme4lme.model$call$randomfindbars(formula(lme4.model))

   random.structures = list(
  "~ b | random1",
  "(b | random1)",
  "~ b + x1 | random1",
  "(b + x1 | random1)",
  "~ x1 + b| random1",
  "(x1 + b| random1)",
  "~ b + x1 + c | random1",
  "(b+ x1 + c | random1)",
  "~b + x1 + x2 | random1",
  "(b + x1 + x2 | random1)",
  "~ x1 + x2 + b | random1",
  "(x1 + x2 + b | random1)"
)

我已经删除了变量b,并c使用dropterms. 由于它们不再作为固定效应存在,因此不应允许它们的随机斜率变化。

b并且c可以使用以下行从上面的随机公式中删除:

random.structures = lapply(random.structures, function(i) gsub("b|c", "", i))

现在,我希望删除所有剩余的+符号,即那些不链接变量的符号。

~然后,如果or(和之间有空格|,我希望插入一个1.

所需的输出是

random.structures2 = list(
  "~ 1 | random1",
  "(1 | random1)",
  "~ x1 | random1",
  "(x1 | random1)",
  "~ x1 | random1",
  "(x1 | random1)",
  "~ x1 | random1",
  "(x1 | random1)",
  "~ x1 + x2 | random1",
  "(x1 + x2 | random1)",
  "~ x1 + x2 | random1",
  "(x1 + x2 | random1)"
)

我一直在摆弄,gsub但似乎无法做到正确。例如,这有效:

gsub("(.*)\\+\\ |(.*)\\+(\\|)", "\\1", random.structures[[3]])
# Accounting for space or lack of space between + and |

但不是为了这个:

gsub("(.*)\\+\\ |(.*)\\+(\\|)", "\\1", random.structures[[7]])

或者,如果有像dropterms随机结构这样的预先存在的功能,我全力以赴!

同样,我不能可靠地将 a 插入到or1之间的空白处。~ |( |

4

1 回答 1

3

起始列表中的一半项目是正确的公式(带有“~”的那些)。我不确定您对括号中的术语做了什么。但是对于公式,您可以使用该Formula包更好地支持删除带有条件项的项。

在这里,我将子集化为正确的公式并转换为Formula对象。

library(Formula)
rx <- lapply(random.structures[grep("~", random.structures)],
    function(x) Formula(as.formula(x)))

我们可以用

sapply(rx, deparse)

# [1] "~b | random1"
# [2] "~b + x1 | random1"
# [3] "~x1 + b | random1"
# [4] "~b + x1 + c | random1"
# [5] "~b + x1 + x2 | random1"
# [6] "~x1 + x2 + b | random1"

现在我们可以从所有这些中删除bc

nx <- lapply(x, function(x) update(x, ~.-b-c))

并查看结果

sapply(nx, deparse)

# [1] "~1 | random1" 
# [2] "~x1 | random1"
# [3] "~x1 | random1"
# [4] "~x1 | random1"
# [5] "~x1 + x2 | random1"
# [6] "~x1 + x2 | random1"

在使用常规公式的地方使用这些应该没有问题。

于 2015-05-07T20:23:41.243 回答