I´m trying to clean the factor variables in a dataframe from trailing spaces. However the levels assignment doesnt work inside my lapply function.
rm.space<-function(x){
a<-gsub(" ","",x)
return(a)}
lapply(names(barn),function(x){
levels(barn[,x])<-rm.space(levels(barn[,x]))
})
Any ideas how I can assign levels inside a lapply function?
//M
From your code I read that the lapply is used to loop over different variables, not over the levels of the factor. So then you do need some kind of looping structure, but lapply is a bad choice:
Anyway, in case you need to assign something to a variable in your global environment within a lapply, you need the <<- operator. Say you need to have a number of variables you selected where the spaces have to be removed:
gives
Better is to use a for loop :
Does what you need without the hassle of the <<- operator and without holding memory unnecessarily.