2013-08-16 268 views
2

我有一個data.frame,其中包含713行,其中一列itemcode有228個唯一代碼。我的問題是,如何爲所有ID創建選擇選項?創建新變量

nrow(test.1) 
[1] 713 

length(unique(test.1$itemcode)) 
[1] 228 

head(test.1) 
     itemcode ID 
2 1180158001 1 
225 1180149701 2 
264 1180074301 3 
522 1180177701 4 
732 1180197201 5 
1182 1170015601 6 

這裏是我的審判代碼:

test$ID <- 1:nrow(test) 
for (i in unique(test$itemcode)) 
    for (j in 1:length(unique(test$itemcode))) 
     test$choice[test$itemcode == i] <- j 

我所需的輸出會是這樣的

 itemcode ID choice 
2 1180158001 1 1 
225 1180149701 2 2 
264 1180074301 3 3 
522 1180177701 4 4 
732 1180197201 5 5 
1182 1170015601 6 6 
523 1180177701 7 4 

這工作。但是如果test.1是測試的一個子集?該代碼將返回測試的下層值。

test$choice <- as.integer(as.factor(test$itemcode)) 
+1

我編輯了格式化和重寫行的問題。但我仍然認爲標題和身體需要改進。 – Arun

+0

我第二@阿倫 - 真的很難分辨你實際上在做什麼。請添加一些所需的輸出,它真的有幫助! –

+0

感謝您的澄清和輸出數據(+1)。我在下面編輯了我的答案。 –

回答

2

想你想factor ...

test$choice <- as.integer(as.factor(test$itemcode)) 

這將打開每一個獨特的itemcode成整數編碼的變量。 as.integer會告訴你底層的價值是什麼。如果您希望他們按照出現在data.frame中的順序進行排序,您需要指定factor變量的levels,您可以使用factor而不是as.factor來執行此操作。

# Turn them into an integer code - ordering is sorted on value of itemcode 
test$choice <- as.integer(as.factor(test$itemcode)) 

# Same, but specify ordering as the values appear in the dataframe 
test$choice2 <- as.integer(factor(test$itemcode , levels = test$itemcode[ ! duplicated(test$itemcode) ])) 

     itemcode ID choice choice2 
2 1180158001 1  4  1 
225 1180149701 2  3  2 
264 1180074301 3  2  3 
522 1180177701 4  5  4 
732 1180197201 5  6  5 
1182 1170015601 6  1  6 
523 1180177701 7  5  4