Using R's lm on a dataframe with a list of predictors

前端 未结 3 656
臣服心动
臣服心动 2020-12-15 21:26

I have a dataframe with let\'s say N+2 columns. The first is just dates (mainly used for plotting later on), the second is a variable whose response to the remaining N colu

3条回答
  •  无人及你
    2020-12-15 22:12

    I am fairly new to R, but I found another way to do this for named columns in a data frame. Say you want to run regression using all columns except for column x2, then you'll write:

    df = data.frame(y = 1:10, x1 = runif(10), x2 = rnorm(10))
    # Removes the column containing x2 so regression on x1 only
    model <- lm(Y ~ . - x2, data = df)
    # to remove more columns (assuming there were more columns in the data frame)
    model <- lm(Y ~ . - x2 - x3 - x4, data = df)
    

    The rest of the answers are pretty old, so maybe it's a new feature, but it's pretty neat!

提交回复
热议问题