When x is in the form of factors,
as.numeric(x) will only give the indices of the levels to which the entries are corresponding.
In order to fix this, what we have to do is to call the level of x, and apply the corresponding index.
That is,
level(x)[x]
will do.
n_to_factor <- function(x){
if(class(x) == 'factor'){
as.numeric(levels(x)[x])
}
else
x
}