创建新变量

时间:2013-08-16 07:15:21

标签: r variables analysis

我有一个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返回底层值。

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

1 个答案:

答案 0 :(得分:2)

我想你想要factor ...

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

这会将每个唯一itemcode转换为整数编码变量。 as.integer将显示基础值是什么。如果您希望它们按data.frame中显示的顺序排序,则需要指定levels变量的factor,并且可以使用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