R当数据为因子时,追加两个data.frames

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

我有两个数据帧,我希望将它们作为一列标签附加到其中;但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)
给我一个奇怪的输出。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,而不是
    数据帧
    s
    rbind
    在这种情况下会做一些完全不同的事情。您可能希望使用
    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)