我有一個資料框,其列包含在不同資料集上訓練的回歸模型的系數。資料幀的每一行對應于在(可能)不同的資料集上訓練的模型。在下面的示例中,我對三行中的每一行都使用了相同的資料集。有多個包含互動項的列。在下面的示例中,僅顯示了具有互動作用項的列。
> models_t
(Intercept) x1 x2 x3 x1:x3
model1.coefficients -0.0231804 1.02417 1.024191 -0.0118544 1.001139
model2.coefficients -0.0231804 1.02417 1.024191 -0.0118544 1.001139
model3.coefficients -0.0231804 1.02417 1.024191 -0.0118544 1.001139
我們正在使用這樣的字串過濾條件:
cond = "x1:x3 > 0"
為了過濾滿足互動效果條件的模型。我們正在使用dplyr和rlang庫,如下所示:
> models_t %>% dplyr::filter(!!rlang::parse_expr(cond))
Error: Problem with `filter()` input `..1`.
? Input `..1` is `x1:x3 > 0`.
x Input `..1` must be of size 3 or 1, not size 2.
Run `rlang::last_error()` to see where the error occurred.
In addition: Warning messages:
1: In x1:x3 : numerical expression has 3 elements: only the first used
2: In x1:x3 : numerical expression has 3 elements: only the first used
可以看出,R 似乎將該x1:x3術語解釋為一個范圍。如何使用字串來參考互動項來執行這樣的過濾操作?
uj5u.com熱心網友回復:
對列名使用反引號。
cond = "`x1:x3` > 0"
然后,您可以在基礎 R 中使用它subset或dplyr::filter-
subset(df, eval(parse(text = cond)))
df %>% dplyr::filter(!!rlang::parse_expr(cond))
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/419375.html
標籤:
上一篇:如何匹配列中的重復值、檢查條件并在R中輸出最終結果?
下一篇:使用stringr提取模式
