user113156
user113156

Reputation: 7107

Making a formula using paste

I am trying to make a formula using R.

I have the following data:

data(iris)
iris <- iris %>%
  select(Species, everything())

I am trying to make a formula based on the colnames. I would like it such that the formula looks like formula <- y ~ x1 + x2 + x3 + x4. I can use the following to get the X variables.

paste("X", seq(2:ncol(iris)), sep = "")

How can I paste the y ~ before them and add the +? I can use collapse but I would like the ~ and the + in the same formula.

Upvotes: 1

Views: 2060

Answers (2)

Ronak Shah
Ronak Shah

Reputation: 388817

It will be simple if we first rename and rearrange the columns using the below or something similar

library(dplyr)
df <- iris %>%
        select(Species, everything()) %>% 
        rename_all(~paste0("X", seq_along(.) - 1)) %>%
        rename(Y = 1)

We could then use reformulate like

reformulate(names(df)[-1], names(df)[1])
#Y ~ X1 + X2 + X3 + X4

We can also use paste0 to create a string as per preference and then use as.formula

as.formula(paste0("Y ~ ", paste0(names(df)[-1], collapse = " + ")))
#Y ~ X1 + X2 + X3 + X4

Upvotes: 4

akrun
akrun

Reputation: 886938

We can use reformulate

reformulate(paste0("X",  head(seq_along(iris), -1)), "y")
#y ~ X1 + X2 + X3 + X4

Upvotes: 1

Related Questions