我有两个数据框,我希望将其作为一个标签列添加到一个数据框中;但是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
如何将两组标签附加到只有一列标签?
答案 0 :(得分:2)
我看到了几个问题:
您发布的str
表示您不是在处理data.frame
,而是vector
。当您在rbind
上使用vector
时,您将获得matrix
作为结果(这是您在“trainPlusTestLabels”str
中看到的内容)。
直接在矩阵中转换factor
,只需抓取基础数值(1和2),因此您必须执行一些as.numeric(as.character(...))
才能获得所需的输出。< / p>
或者,您可以在unlist
向量上使用list
。尝试:
unlist(list(trainLabels, testLabels), use.names = FALSE)
请注意,这仍会产生vector
,而不是data.frame
: - )