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))
我编辑了格式化和重写行的问题。但我仍然认为标题和身体需要改进。 – Arun
我第二@阿伦 - 真的很难分辨你实际上在做什么。请添加一些所需的输出,它真的有帮助! –
感谢您的澄清和输出数据(+1)。我在下面编辑了我的答案。 –