【问题标题】:Create new variable创建新变量
【发布时间】: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)。我在下面编辑了我的答案。

标签: r variables analysis


【解决方案1】:

认为你想要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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-14
    • 1970-01-01
    • 2018-06-05
    • 1970-01-01
    • 1970-01-01
    • 2014-08-03
    相关资源
    最近更新 更多