2013-08-16 277 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