Добавление к ответу @ joran, в котором convert.magic
не будет сохранять числовые значения при преобразовании коэффициента в цифру:
convert.magic <- function(obj,types){
out <- lapply(1:length(obj),FUN = function(i){FUN1 <- switch(types[i],
character = as.character,numeric = as.numeric,factor = as.factor); FUN1(obj[,i])})
names(out) <- colnames(obj)
as.data.frame(out,stringsAsFactors = FALSE)
}
foo<-data.frame(x=c(1:10),
y=c("red", "red", "red", "blue", "blue",
"blue", "yellow", "yellow", "yellow",
"green"),
z=Sys.Date()+c(1:10))
foo$x<-as.character(foo$x)
foo$y<-as.character(foo$y)
foo$z<-as.numeric(foo$z)
str(foo)
# 'data.frame': 10 obs. of 3 variables:
# $ x: chr "1" "2" "3" "4" ...
# $ y: chr "red" "red" "red" "blue" ...
# $ z: num 16777 16778 16779 16780 16781 ...
foo.factors <- convert.magic(foo, rep("factor", 3))
str(foo.factors) # all factors
foo.numeric.not.preserved <- convert.magic(foo.factors, c("numeric", "character", "numeric"))
str(foo.numeric.not.preserved)
# 'data.frame': 10 obs. of 3 variables:
# $ x: num 1 3 4 5 6 7 8 9 10 2
# $ y: chr "red" "red" "red" "blue" ...
# $ z: num 1 2 3 4 5 6 7 8 9 10
# z comes out as 1 2 3...
Ниже следует сохранить числовые значения:
## as.numeric function that preserves numeric values when converting factor to numeric
as.numeric.mod <- function(x) {
if(is.factor(x))
as.numeric(levels(x))[x]
else
as.numeric(x)
}
## The same than in @joran's answer, except for as.numeric.mod
convert.magic <- function(obj,types){
out <- lapply(1:length(obj),FUN = function(i){FUN1 <- switch(types[i],
character = as.character,numeric = as.numeric.mod, factor = as.factor); FUN1(obj[,i])})
names(out) <- colnames(obj)
as.data.frame(out,stringsAsFactors = FALSE)
}
foo.numeric <- convert.magic(foo.factors, c("numeric", "character", "numeric"))
str(foo.numeric)
# 'data.frame': 10 obs. of 3 variables:
# $ x: num 1 2 3 4 5 6 7 8 9 10
# $ y: chr "red" "red" "red" "blue" ...
# $ z: num 16777 16778 16779 16780 16781 ...
# z comes out with the correct numeric values