Working dollar
Working dollar

Reputation: 296

Iterate a string into formula

I want to iterate over a list of strings and append these to my formula one by one and adding the extra name after each iteration. For example, my code produces the following output:

require(faraway)
col_names <- names(teengamb)[-5]
form <-0
for(i in 1:length(col_names)){
  form[i]=list(formula(paste('gamble ~', paste(col_names[i], collapse='+'))))
  
}
[[1]]
gamble ~ sex

[[2]]
gamble ~ status

[[3]]
gamble ~ income

[[4]]
gamble ~ verbal

Expected output:

[[1]]
gamble ~ sex

[[2]]
gamble ~ sex+status

[[3]]
gamble ~ sex+status+income

[[4]]
gamble ~ sex+status+income+verbal

Upvotes: 2

Views: 80

Answers (2)

Rui Barradas
Rui Barradas

Reputation: 76621

Though there already is an accepted answer, here is a way with reformulate.

data(teengamb, package = "faraway")

col_names <- names(teengamb)[-5]

form <- vector("list", length(col_names))
for(i in seq_along(col_names)){
  form[[i]] <- reformulate(col_names[1:i], response = "gamb")
}
form
#> [[1]]
#> gamb ~ sex
#> 
#> [[2]]
#> gamb ~ sex + status
#> 
#> [[3]]
#> gamb ~ sex + status + income
#> 
#> [[4]]
#> gamb ~ sex + status + income + verbal

Created on 2022-06-04 by the reprex package (v2.0.1)


And here is another one, this time with purrr::map.

form_function <- function(i, response = "gamb") {
  reformulate(col_names[1:i], response = response)
}

col_names |>
  seq_along() |>
  purrr::map(form_function)
#> [[1]]
#> gamb ~ sex
#> <environment: 0x0000026801da3030>
#> 
#> [[2]]
#> gamb ~ sex + status
#> <environment: 0x0000026801d924f8>
#> 
#> [[3]]
#> gamb ~ sex + status + income
#> <environment: 0x0000026801c0c870>
#> 
#> [[4]]
#> gamb ~ sex + status + income + verbal
#> <environment: 0x0000026801c13e80>

Created on 2022-06-04 by the reprex package (v2.0.1)

Or a base R only way with the new pipe operator, introduced in R 4.2.0,

col_names |>
  seq_along() |>
  lapply(form_function) 

Upvotes: 2

PaulS
PaulS

Reputation: 25393

A possible solution (we need to replace col_names[i] by col_names[1:i]):

require(faraway)
#> Loading required package: faraway
col_names <- names(teengamb)[-5]
form <-""
for(i in 1:length(col_names)){
  form[i]=list(formula(paste('gamble ~', paste(col_names[1:i], collapse='+'))))
  
}

form

#> [[1]]
#> gamble ~ sex
#> 
#> [[2]]
#> gamble ~ sex + status
#> 
#> [[3]]
#> gamble ~ sex + status + income
#> 
#> [[4]]
#> gamble ~ sex + status + income + verbal

Upvotes: 2

Related Questions