R当数据为因子时,追加两个data.frames
我有两个数据帧,我希望将它们作为一列标签附加到其中;但rbind并没有像预期的那样发挥作用,可能是因为数据是:R当数据为因子时,追加两个data.frames,r,R,我有两个数据帧,我希望将它们作为一列标签附加到其中;但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
> 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)
给我一个奇怪的输出。TrainPlustestLabel没有我想要的结构
> 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
如何将两组标签附加到一列标签上?我发现了几个问题:
str
表明您不是在处理data.frame
s,而是vector
s。当您在vector
s上使用rbind
时,您将得到一个矩阵
(这是您在“trainPlusTestLabels”str
中看到的结果)因子
s只会获取底层的数值(1和2),因此您必须将转换为.numeric(as.character(…)
,以获得所需的输出列表上使用unlist
。尝试:
unlist(list(trainLabels, testLabels), use.names = FALSE)
注意,这仍然会产生一个向量
,而不是数据帧
:-)在我看来,“火车标签”和“测试标签”是向量
s,而不是数据帧
srbind
在这种情况下会做一些完全不同的事情。您可能希望使用c()
组合2个向量……或者data.frame(train=trainLabels,test=testLabels)
如果您希望它们作为数据帧中的列。@tcash21,如果使用c()
它们必须首先转换为字符。最好使用unlist(list(trainLabels,testLables),use.names=FALSE)
@tcash21 c()给我的值类似于2,此时标签应仅为“0”或“1”。也可以使用as.vector()
,因为有一个as.vector.factor
在“correct”中应用as.numeric(as.character()
)DWIM时尚。@DWin,我不太明白。你是说类似于c(as.vector(trainLabels),as.vector(testLabels))
?这是可行的,但给了我一个字符向量作为输出。这不是需要的字符向量吗?@DWin,我认为需要一个因子向量,你可以在我的回答中通过取消列表…
方法得到。哈。这对我来说有点意外。我现在也理解了你关于rbind.data.frame
的观点。在家里的孩子们,阿南达真的在做一些重要的事情。
unlist(list(trainLabels, testLabels), use.names = FALSE)