[R] Reorder factor and address embedded escapes

Rob James rob at aetiologic.ca
Fri Dec 10 21:14:04 CET 2010

I am trying to reorder a factor variable that has embedded escape 
characters.  The data begins as a csv file with a factor that includes 
embedded new line characters.  By the time read.table has rendered it 
into a data frame, the variable now has an extra backslash.

"This\nLabel" in the csv becomes "This\\nLabel" in the data frame.

So, I am trying to reorder the factor and deal with the introduction of 
a secondary  \ .   Here's a small example:

A = c("A\\nB", "C\\nD")
test <-data.frame(A)
test$reorderA <-factor(test$A, c("C\\nD", "A\\nB"))
test$reorderB <-sub("\\\\n", "\n", test$reorderA)

When sub is applied to the now-correctly ordered factor, it returns to 
the default ordering.


More information about the R-help mailing list