Search code examples
rstringcommentsline-breaks

Assigning `comment()` to an R object from a .txt file


I am trying to assign a comment to a data frame to store some relevant metadata. I have an unstructured text file wrapped in quote marks, with several line breaks ('\n').

WHO_comment<-read.table(file="WHO comment.txt", sep="\t")
comment(WHO)<-WHO_comment #Read in the comment from .txt due to its length
cat(comment(WHO)) #Database metadata

However, the readout comes in one large block with '\n' read as literal strings. Converting it with as.character() only returns the row name (i.e. '1').

How can I read in this file correctly?


Solution

  • read.table is the wrong function to read a text file. As the name suggests, its purpose is to read tabular data. To read a text file, use readLines, and then paste the individual lines together:

    comment(data) = paste(readLines('WHO comment.txt'), collapse = '\n')