我从文本创建公式,但结果公式包含不需要的空格。有没有办法防止这种情况。
# text in which variables for formula are stored
mainEffectText ="age sex bmi cohort"
interactionText="age*cohort"
# get text into R
mainEffects <- read.table(textConnection(mainEffectText))
mainEffects <- t(mainEffects)
mainEffects <- as.character(mainEffects[,1])
interactions <- read.table(textConnection(interactionText))
interactions <- t(interactions)
interactions <- as.character(interactions[,1])
# put all terms into one vector
allTerms <- c(mainEffects,interactions)
# create formula
form <- as.formula(paste("Surv(time, event) ~ ",paste(allTerms, collapse=" +")))
以下为交互术语添加了空格:
form
# Surv(time, event) ~ age + sex + bmi + cohort + age * cohort
答案 0 :(得分:0)
这些空间并不是真正的问题,但无论如何都要尝试这个:
# inputs
mainEffectText <- "age sex bmi cohort"
interactionText <- "age*cohort"
lhs <- "Surv(time, event)"
both <- paste(mainEffectText, interactionText)
paste0(gsub(" ", "", lhs), "~", gsub(" ", "+", both))
,并提供:
"Surv(time,event)~age+sex+bmi+cohort+age*cohort"
如果输入采用此格式(lhs
如上),请使用:
# inputs
mainEffects <- c("age", "sex", "bmi", "cohort")
interactions <- "age*cohort"
both <- paste(paste(mainEffects, collapse = " "),
paste(interactions, collapse = " "))
paste0(gsub(" ", "", lhs), "~", gsub(" ", "+", both))