【发布时间】:2013-08-18 12:51:35
【问题描述】:
我有一个 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 ) )
【问题讨论】:
-
我已经编辑了格式化问题并重写了这些行。但我仍然认为标题和正文需要改进。
-
我第二个 @Arun - 真的很难说你到底在追求什么。请添加一些所需的输出,这真的很有帮助!
-
感谢您的澄清和输出数据 (+1)。我在下面编辑了我的答案。