Thanks to 42's comment, I've managed to write a function to recode the file:
fix.encoding <- function(df, originalEncoding = "latin1") {
numCols <- ncol(df)
for (col in 1:numCols) Encoding(df[, col]) <- originalEncoding
return(df)
}
The meat here is the command Encoding(df[, col]) <- "latin1"
, which takes column col
of dataframe df
and converts it to latin1 format. Unfortunately, Encoding
only takes column objects as input, so I had to create a function to sweep all columns of a dataframe object and apply the transformation.
Of course, if your problem is in just a couple of columns, you're better off just applying the Encoding
to those columns instead of the whole dataframe (you can modify the function above to take a set of columns as input). Also, if you're facing the inverse problem, i.e. reading an R object created in Linux or Mac OS into Windows, you should use originalEncoding = "UTF-8"
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…