【问题标题】:R append two data.frames when data are factors当数据是因素时,R附加两个data.frames
【发布时间】:2013-10-21 15:26:36
【问题描述】:

我有两个数据框,我希望将它们作为一列标签附加到一个中;但是 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

如何将两组标签附加到只有一列标签?

【问题讨论】:

  • 在我看来,“trainLabels”和“testLabels”是vectors,而不是data.frames。 rbind 在这种情况下会做一些完全不同的事情。
  • 你想使用c() 来组合两个向量。
  • ...或data.frame(train = trainLabels,test = testLabels),如果您希望它们作为数据框中的列。
  • @tcash21,如果使用c(),他们必须先转换为character。最好使用unlist(list(trainLabels, testLables), use.names = FALSE)
  • @tcash21 c() 给了我像 2 这样的值,而标签只能是“0”或“1”。

标签: r


【解决方案1】:

我看到的几个问题:

  1. 你发的str表明你不是在处理data.frames,而是vectors。当您在vectors 上使用rbind 时,您将得到matrix 作为结果(这是您在“trainPlusTestLabels”str 中看到的内容)。

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

或者,您可以在向量的list 上使用unlist。试试:

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

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

【讨论】:

  • 也可以使用as.vector(),因为有一个as.vector.factor,该方法以“正确”的DWIM方式应用as.numeric(as.character(.))
  • @DWin,不确定我是否遵循。你是在说c(as.vector(trainLabels), as.vector(testLabels)) 之类的话吗?这可行,但给了我一个字符向量作为输出。
  • 不是需要一个字符向量吗?
  • @DWin,我认为需要一个 factor 向量,您可以在我的回答中使用 unlist... 方法获得它。
  • 嗯。这对我来说有点意外。我现在也理解你对rbind.data.frame 的看法了。孩子们在家,阿难在这里真的很重要。
猜你喜欢
  • 2021-03-08
  • 1970-01-01
  • 2023-03-12
  • 2013-01-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多