如何从R中的公式中提取子集

时间:2017-08-19 17:49:47

标签: r formula

假设我有一个公式:<Window x:Class="UI.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:xcdg="http://schemas.xceed.com/wpf/xaml/datagrid" xmlns:xctk="http://schemas.xceed.com/wpf/xaml/toolkit" mc:Ignorable="d" Title="MainWindow" Height="800" Width="700"> <Grid> <xctk:Zoombox MinScale="0.5" MaxScale="100" > <Grid Width="600" Height="400" Background="Yellow"> <Ellipse Fill="Blue" /> </Grid> </xctk:Zoombox> </Grid> </Window> ,我想随机选择其中两个预测变量来制作formula = Y ~ X1 + X2 + X3 + X4 + X5。我怎么会这样做?

2 个答案:

答案 0 :(得分:3)

使用reformulate创建公式。将预测变量放在矢量中,然后使用sample

选择随机变量
vars = c("X1", "X2", "X3", "X4", "X5")
#If you already have the formula, you can do 
#vars = all.vars(formula)[-1]

set.seed(40)
reformulate(termlabels = sample(vars, 2), response = "y")
#y ~ X4 + X5

set.seed(35)
reformulate(termlabels = sample(vars, 2), response = "y")
#y ~ X5 + X1

答案 1 :(得分:1)

d.b答案的一个小附录:如果未知预测变量的名称,您可以使用

公式中检索它们
vars = attr(terms(formula), 'term.labels')