将一列data.frame转换为factor

时间:2020-12-05 22:51:35

I have the following data.frame:

我有以下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.

但这似乎不起作用;它确实改变了结构,但它仍然不是我想要的。

1 个解决方案

#1


1  

Instead of reassigning back into the data.frame column,

而不是重新分配回data.frame列,

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.

请注意,在您的要求中,原始trainLabels是data.frame,而最终输出是向量。它们是两个完全不同的对象,分配给同一个名称,后者覆盖前者。

#1


1  

Instead of reassigning back into the data.frame column,

而不是重新分配回data.frame列,

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.

请注意,在您的要求中,原始trainLabels是data.frame,而最终输出是向量。它们是两个完全不同的对象,分配给同一个名称,后者覆盖前者。