views:

223

answers:

2

Hello,

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!

+1  A: 

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)
kohske
+4  A: 
for (i in names(UNCA)) {
    UNCA[,paste(i,"F",sep='.')] <- as.factor(UNCA[,i])
}
gd047
Thank you for the response. Someone had suggested something similar to this earlier and for some reason this gives me an "unexpected input" error.
Michael
@Michael So why you don't ask in your previous question? This question is almost identical to your previous question.
Marek