【发布时间】:2015-06-19 09:08:38
【问题描述】:
我正在寻找一种智能方法来索引数据框中的子类别。
我在下面创建了一个非常简单的可重现示例。您将如何编码以下步骤以从输入到输出(即我们如何编码创建 color_id 变量)?
非常感谢您对此的看法!
input <- data.frame(label = c("red", "red", "blue", "green", "green", "green", "orange"), count = c(2, 2, 1, 3, 3 ,3, 1))
output <- data.frame(label = c("red", "red", "blue", "green", "green", "green", "orange"), count = c(2, 2, 1, 3, 3 ,3, 1), color_id = c(1, 2, 1, 1, 2, 3, 1))
最好的问候
【问题讨论】:
-
我目前找不到合适的骗子。在基础 R 中,您可以使用
?ave,例如:within(input, color_id <- ave(seq_along(label), label, FUN = seq_along)),但还有许多其他方法可以做到这一点。在 dplyr:input %>% group_by(label) %>% mutate(color_id = row_number()) -
@DavidArenburg 这是我使用的一个特例,但你链接的答案确实直接回答了这个问题。我该如何切换欺骗?
-
我认为
splitstackshape有一个getanid功能。