5
I want to create a function that facilitates my life when treating some variables
I want a function that receives as input a database, a column or variable u of that database, a vector c specifying the levels to be exchanged and the new name that will replace such levels.
Actually, I tried to do this directly with relevel function, but I didn’t find it very easy to use.
I created a function that returns me a vector type factor... but actually, I want the function to transform the data Matrix so that the variable u is already modified... because after using my function and I give a levels(data$u) appear the old levels
juntar<- function(data, u, c , novolevel)
{
### Trasformamos nossa variável em tipo character
data[,which(colnames(data)== u )]<- as.character(data[,which(colnames(data)== u )])
levels<- c
### determinamos as coordenadas levels
coordenadas_levels<- data[,which(colnames(data)== u )] %in% levels
coordenadas_levels<- which(coordenadas_levels == TRUE)
### Fazemos a mudança
data[,which(colnames(data)== u )][coordenadas_levels]<- novolevel
### Convertemos em factor
data[,which(colnames(data)== u )]<- as.factor(data[,which(colnames(data)== u )])
}
Thank you