2013-10-21 51 views
1

我有兩個數據幀,我希望將其作爲一個標籤列添加到一個數據幀中;但rbind不能按預期工作,可能是因爲數據的因素:R當數據是因素時附加兩個數據幀

> 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

它看起來* *我喜歡 「trainLabels」 和 「testLabels」 是'vector's,不'數據.frame's。在這種情況下,'rbind'會做出完全不同的事情。 – A5C1D2H2I1M1N2O1R2T1

+0

你會想用'c()'來組合2個向量。 – tcash21

+0

...或者'data.frame(train = trainLabels,test = testLabels)'如果你想讓它們作爲數據框中的列。 – joran

回答

2

一對夫婦的問題,我看到:

  1. str你後表示您不處理data.frame S,但vector秒。當您在vector上使用rbind時,您會得到一個matrix(這是您在「trainPlusTestLabels」str中看到的內容)。

  2. factor直接轉換成矩陣,就像抓取底層數值(1和2)一樣,因此您需要做一些as.numeric(as.character(...))以獲得所需的輸出。

或者,您可以使用unlist上載體的list。嘗試:

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

注意,這仍然導致vector,不是data.frame :-)

+0

也可以使用'as.vector()',因爲有一個'as.vector.factor'方法以「正確的」DWIM方式應用「as.numeric(as.character(。))」。 –

+0

@DWin,不知道我關注。你在說'c(as.vector(trainLabels),as.vector(testLabels)')嗎?這有效,但給我一個字符向量作爲輸出。 – A5C1D2H2I1M1N2O1R2T1

+0

是不是一個人物矢量需要什麼? –