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?

4

1 回答 1

9

您可以在 R 中进行后处理。而不是文件,将输出存储在使用capture.output. 使用 删除反引号gsub。最后,使用以下命令将输出打印到文件中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")
于 2013-05-08T00:46:12.480 回答