开发者

R question. Using lappy on a data.frame and creating new variables w/ output

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 appreciat开发者_开发知识库ed!


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


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)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜