简体   繁体   中英

Convert one column data.frame into factor

I have the following data.frame:

> str(trainLabels)
'data.frame':   1000 obs. of  1 variable:
 $ V1: int  1 0 0 1 0 1 0 1 1 0 ...

I wish to obtain a factor as follows:

> str(trainLabels)
 Factor w/ 2 levels "0","1": 1 0 0 1 0 1 0 1 1 0 ...

I have tried:

trainLabels$V1 <- as.factor(trainLabels$V1)

but that doesn't seem to work; it does change the structure, but it's still not what I want.

Instead of reassigning back into the data.frame column,

trainLabels <- as.factor(trainLabels$V1)

Note that in your requirements, the original trainLabels is a data.frame whereas the final output is a vector. They are two completely different objects being assigned to the same name, the latter overwriting the former.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM