Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing backticks in R output

Tags:

r

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?

like image 400
JasonMond Avatar asked May 08 '13 00:05

JasonMond


1 Answers

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")
like image 143
flodel Avatar answered Sep 17 '22 23:09

flodel