Kelsey
Kelsey

Reputation: 199

Create text string from character vector in R

I have character vectors of varying lengths and I would like to use them to create a formula for a regression model.

fifty <- c("AstheniaWeakness", "Breathlessness", "CT", "PatientAge")

The desired output would be:

Death ~ AstheniaWeakness + Breathlessness + CT + PatientAge

I have tried combinations of map and lapply with paste0 but these are not working.

Upvotes: 1

Views: 353

Answers (2)

akrun
akrun

Reputation: 887951

We could use reformulate

reformulate(fifty, response = 'Death')
Death ~ AstheniaWeakness + Breathlessness + CT + PatientAge

Upvotes: 2

r2evans
r2evans

Reputation: 161110

paste("Death ~", paste(fifty, collapse = " + "))
# [1] "Death ~ AstheniaWeakness + Breathlessness + CT + PatientAge"

It's a two-step procedure: the first step combines the vector and collapses them with a particular string, " + ":

paste(fifty, collapse = " + ")
# [1] "AstheniaWeakness + Breathlessness + CT + PatientAge"

then we need to prepend "Death ~" before that.

Upvotes: 2

Related Questions