我正在寻找一种解决方案来添加列“desired_result”,最好使用 dplyr 和/或 ave()。请参阅此处的数据框,其中组是“部分”,我希望我的“desired_results”列按顺序计数的唯一实例在“展示”中:
structure(list(section = c(1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L), exhibit = structure(c(1L,
2L, 3L, 3L, 1L, 2L, 2L, 3L), .Label = c("a", "b", "c"), class = "factor"),
desired_result = c(1L, 2L, 3L, 3L, 1L, 2L, 2L, 3L)), .Names = c("section",
"exhibit", "desired_result"), class = "data.frame", row.names = c(NA,
-8L))
最佳答案
dense_rank
是
library(dplyr)
df %>%
group_by(section) %>%
mutate(desire=dense_rank(exhibit))
# section exhibit desired_result desire
#1 1 a 1 1
#2 1 b 2 2
#3 1 c 3 3
#4 1 c 3 3
#5 2 a 1 1
#6 2 b 2 2
#7 2 b 2 2
#8 2 c 3 3
关于R - 添加在组内按顺序计数但重复的列,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27895860/