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:
- you loop over a vector -names(barn)- so it's better to use sapply
- the apply family will return the result from each loop, something you don't want. So you're using memory without purpose.
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:
f <- paste("",letters[1:5])
Df <- data.frame(
X1 = sample(f,10,r=T),
X2 = sample(f,10,r=T),
X3 = sample(f,10,r=T)
)
# Bad example :
lapply(c("X1","X3"),function(x){
levels(Df[,x])<<-gsub(" +","",levels(Df[,x]))
})
gives
> str(Df)
'data.frame': 10 obs. of 3 variables:
$ X1: Factor w/ 3 levels "a","b","c": 2 3 1 1 1 2 3 2 2 2
$ X2: Factor w/ 5 levels " a"," b"," c",..: 4 5 4 2 5 5 1 2 5 3
$ X3: Factor w/ 5 levels "a","b","c","d",..: 2 3 4 1 4 1 3 3 5 4
Better is to use a for loop :
for( i in c("X1","X3")){
levels(Df[,i])<-gsub(" +","",levels(Df[,i]))
}
Does what you need without the hassle of the <<- operator and without holding memory unnecessarily.