【发布时间】:2015-03-09 20:34:54
【问题描述】:
我正在寻找一种解决方案来添加列“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))
【问题讨论】:
-
df$desired <- c("a"=1, "b"=2, "c"=3)[df$exhibit] -
我认为您的“规则”不够清晰。您的数据是否已排序,就像您在此处的示例数据集中一样?
-
@Khashaa 抱歉,出于示例数据框的目的,我将全名缩短为单个字母。有很多名字,所以我需要处理更多的实例,而不仅仅是 3 个。
-
@Ananda Mahto,这些名称不是按字母顺序排列的,而是随机出现的,所以你是对的,我的数据框具有误导性。重要的部分是,当展览列中的计数达到重复时,它应该重复。