R question. Using lappy on dataframe and creating new w / output variables

I have 13 quantitative variables in a data.frame (called UNCA).

The variables are named q01_a, q01_b, ... q01_m.

I want to create 13 new variables that have the same values ​​but are encoded as a factor.

I would call these 13 new variables q01_a.F, q01_b.F, ... q01_m.F.

Any help would be greatly appreciated!

+2


a source to share


2 answers


for (i in names(UNCA)) {
    UNCA[,paste(i,"F",sep='.')] <- as.factor(UNCA[,i])
}

      



+4


a source


this is not a pretty solution, but you can do



d<-data.frame(matrix(sample(26),ncol=13))
names(d)<-paste("q01_",letters[1:13],sep="")

d2<-data.frame(lapply(d,factor))
# or if each variable should have common levels of factor:
# d2<-data.frame(lapply(d,factor, levels=sort(unique(unlist(d)))))

names(d2)<-paste(names(d),"F",sep=".")
d<-cbind(d,d2)

      

+2


a source







All Articles