2

713 行を含むがあり、data.frameその列の 1 つにitemcode228 の一意のコードがあります。私の質問は、すべての 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 のサブセットであるとしたら? このコードは、テストから基礎となる値を返します。

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

1 に答える 1

2

私はあなたが欲しいと思うfactor...

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

これにより、それぞれの一意itemcodeが整数コード変数に変わります。はas.integer、基礎となる値が何であるかを示します。に表示されるように並べ替えたい場合は、変数data.frameの を指定する必要があり、ではなくを使用してこれを行うことができます。levelsfactorfactoras.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
于 2013-08-16T07:20:47.350 に答える