1

我有两个数据框,我希望将它们作为一列标签附加到一个中;但 rbind 没有按预期工作,可能是因为数据是因素:

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

> str(testLabels)
 Factor w/ 2 levels "0","1": 2 1 2 1 1 1 1 2 1 1 ...
> head(testLabels)
[1] 1 0 1 0 0 0
Levels: 0 1

trainPlusTestLabels <- rbind(trainLabels, testLabels)

然后:

head(trainPlusTestLabels)

给了我一个奇怪的输出。trainPlusTestLabels 没有我想要的结构。

> str(trainPlusTestLabels)
 int [1:2, 1:9000] 2 2 1 1 1 2 2 1 1 1 ...
 - attr(*, "dimnames")=List of 2
  ..$ : chr [1:2] "trainLabels" "testLabels"
  ..$ : NULL

如何附加两组标签以仅包含一列标签?

4

1 回答 1

2

我看到的几个问题:

  1. 您发布的str内容表明您不是在处理data.frames,而是在处理vectors。当您使用rbindon vectors 时,您将得到 amatrix作为结果(这是您在 "trainPlusTestLabels" 中看到的str)。

  2. 像这样直接在矩阵中转换factors 只会获取基础数值(1 和 2),因此您必须做一些事情as.numeric(as.character(...))才能获得所需的输出。

或者,您可以unlistlist您的向量上使用。尝试:

unlist(list(trainLabels, testLabels), use.names = FALSE)

请注意,这仍然会导致 a vector,而不是 a data.frame:-)

于 2013-10-21T15:43:36.977 回答