mercredi 19 avril 2017

Function to change class of columns in R to match the class of an other dataset

I am trying to write a function that changes the class of the variables in a dataset in order to match the class of the column of an other dataset.

By example, if I have a dataset 1 with a column named A which as a class factor, and a dataset 2 with a column named A which has a class character, I want to change the class of the column A in dataset 2 to factor.

I have a code, but I don't understand why, it fails to change the classe. Do you have any idea?

change_class2=function(predict_set,train_set){
  col_drop=c()
  for(column in colnames(predict_set)){
    if(!column %in% colnames(train_set))
    {col_drop=c(col_drop,column)}

v=grep(column, colnames(predict_set))
w=grep(column, colnames(train_set))

if((class(predict_set[,v])!=class(train_set[,w]))*(is.factor(train_set[,w]))==1){
  predict_set[,v]=factor(predict_set[,v])}
else if((class(predict_set[,v])!=class(train_set[,w]))*(is.character(train_set[,w]))==1){
  predict_set[,v]=as.character(predict_set[,v])}
else if((class(predict_set[,v])!=class(train_set[,w]))*(is.numeric(train_set[,w]))==1){
  predict_set[,v]=as.numeric(predict_set[,v])}
else if((class(predict_set[,v])!=class(train_set[,w]))*(is.integer(train_set[,w]))==1){
  predict_set[,v]=as.integer(predict_set[,v])}
else{
  predict_set[,v]=predict_set[,v]}

} }






Comments
0 Comments

0 commentaires:

Enregistrer un commentaire