Question

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 coded as a factor.

I would like to name these 13 new variables q01_a.F, q01_b.F, ...q01_m.F.

Any help would be greatly appreciated!

Was it helpful?

Solution

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

OTHER TIPS

this is not a beautiful solution but you can do by

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)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top