Add vector of strings to a formula

Hi all,

I have a formula that I want to modify with a string variable. For some reason, when I try to modify it, a list object is created instead of a formula. The code I;ve written feels awkward, if someone has a solution or even better suggestion to get me what I need.

Thanks in advance,
Kenneth

# this is the formula I start with
> design(dds)
~trial + trial:condition
> class(design(dds))
[1] "formula"

# this is the variable I want to append with
> colnames(ruv_s_cov)
[1] "W_1" "W_2"
> class(colnames(ruv_s_cov))
[1] "character"

# this is what I want
>design(dds)
~ trial + trial:condition + W_1 + W_2
> class(design(dds))
[1] "formula"

# this is how it would be done manually 
# ...which I don't want to do because I could be adding anything up to W_20
design(dds) <- ~ trial + trial:condition + W_1 + W_2

This is closest attempt but it adds "list()" to the end:

> as.formula(cat(cat(as.character(design(dds))), as.character(colnames(ruv_s_cov)), sep = " + "))
~ trial + trial:condition + W_1 + W_2list()
> design(dds) <- as.formula(cat(cat(as.character(design(dds))), as.character(colnames(ruv_s_cov)), sep = " + "))
~ trial + trial:condition + W_1 + W_2
> class(design(dds))
[1] "formula"
> design(dds)
list()          # what I want printed: ~ trial + trial:condition + W_1 + W_2

Here is how I would do it with some extra print steps for clarity. I'm not sure it is any more elegant than what you have.

#Invent some objects to work with
FORM <- as.formula("~trial + trial:condition")
class(FORM)
#> [1] "formula"
DF <- data.frame(W_1 = 1, W_2 = 2)
colnames(DF)
#> [1] "W_1" "W_2"


as.character(FORM)
#> [1] "~"                       "trial + trial:condition"
ELEMENTS <- c(as.character(FORM)[-1], colnames(DF))
ELEMENTS
#> [1] "trial + trial:condition" "W_1"                    
#> [3] "W_2"
ELEMENTS <- paste(ELEMENTS, collapse = " + ")
ELEMENTS <- paste0("~", ELEMENTS)
NewFORM <- as.formula(ELEMENTS)
NewFORM
#> ~trial + trial:condition + W_1 + W_2

Created on 2024-08-10 with reprex v2.0.2

1 Like

Thank you, I forgot about collapse!

# code expanded for clarity
> design(dds)
~trial + trial:condition
> colnames(ruv_s_cov)
[1] "W_1" "W_2"
> x <- as.character(design(dds))
> x <- paste(x, collapse = "")
> y <- colnames(ruv_s_cov)
> y <- paste(y, collapse = " + ")
> z <- paste(x, y, sep = " + ")
> design(dds) <- as.formula(z)
> design(dds)
~trial + trial:condition + W_1 + W_2

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.