Molly_K
Molly_K

Reputation: 313

Use "paste" to generate function in r

I plan to use paste to generate a formula but I only know how to do the first half. The first half is Surv(age, group)~x; but how do I add on the second half which makes the final product as Surv(age, group)~x + strata(factor(gender), bmi)?

This is what I have at the moment and it does not work...

tmpfun <- function(x) as.formula(c(paste("Surv(age, group)", x , sep="~"), paste0("+ strata(factor(gender), bmi)")))

Upvotes: 0

Views: 110

Answers (2)

Scott Warchal
Scott Warchal

Reputation: 1028

You can pass more than 2 arguments to paste.

tmpfun <- function(x) {
    as.formula(
        paste("Surv(age, group) ~", x, "+ strata(factor(gender), bmi)")
    )
}

Though sprintf might be a bit tidier.

tmpfun <- function(x) {
    as.formula(
        sprintf("Surv(age, group) ~ %s + strata(factor(gender), bmi)", x)
    )
}

Upvotes: 1

Rui Barradas
Rui Barradas

Reputation: 76673

You were almost there. I've just changed paste0 place.

tmpfun <- function(x) as.formula(paste0(paste("Surv(age, group)", x , sep="~"), "+ strata(factor(gender), bmi)"))

Upvotes: 1

Related Questions