6

I have certain variables that lm in R automatically wraps with backticks/back quotes, e.g. variables that have colons in the names.

After some processing, I'm trying to write out the variables and coefficients of the linear model with write.table. Unfortunately, the backticks are written out as well.

How can I prevent these backticks from being written?

To give a simple but unrealistic example:

d <- data.frame(`1`=runif(10), y=runif(10), check.names=F)
l <- lm(y ~ `1`, d)
write.table(data.frame(l$coefficients), file="lm.coeffs", quote=F, sep="\t", col.names=F)

The file lm.coeffs will--quite obviously--have `1` in the first column of the output rather than 1. Outside of postprocessing in some other script, how do I remove backticks from output?

JasonMond
  • 1,440
  • 1
  • 16
  • 30

1 Answers1

9

You can do that post-processing in R. Instead of a file, store the output in a variable using capture.output. Remove the backticks using gsub. Finally, print the output to a file using cat:

report <- capture.output(write.table(data.frame(l$coefficients),
                         quote = FALSE, sep = "\t", col.names = FALSE))

cat(gsub("`", "", report), sep = "\n", file = "lm.coeffs")
flodel
  • 87,577
  • 21
  • 185
  • 223