r - 创建新变量

标签 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  

This works. But if test.1 is a subset of test? This code would return the underlaying values from test.

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

最佳答案

认为你想要因素...

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

关于r - 创建新变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18267821/

相关文章:

r - 对从批处理文件运行 R 与直接从 shell 运行 R 之间的区别感到困惑

php - 访问 $_POST 变量导致错误

c# - 数据表中的计算

time-complexity - 时间复杂度 : O(logN) or O(N)?

从整个数据帧中删除 R 中的特定值

r - 使用所有输入变量的神经网络?

r - 在 R 中将 cURL 转换为 httr

java - 变量初始化

使用变量的 PHP SQL 更新

algorithm - 证明表达式的运行时间