我有一个数据框,我试图将 ID 分配给新列(1 到所需的任意数量)。为此,我想按具有相同 ID、数据和示例的所有行进行分组。所以在这里,我希望每次看到一个 id 时都进行分组,然后对我们在该 id 中看到的不同位置进行排名,以创建一个位置 id。我在这个数据集下添加了一个我正在寻找的示例。
id city location locationid
20 london central
20 london north
20 london south
25 birmingham north
25 birmingham south
25 birmingham east
30 manchester greater
30 manchester north
30 manchester east
30 manchester west
33 liverpool central
33 liverpool east
我在寻找什么
id city location locationid
20 london central 1
20 london north 2
20 london south 4
25 birmingham north 2
25 birmingham south 4
25 birmingham east 3
30 manchester greater 1
30 manchester north 2
30 manchester east 3
30 manchester west 5
33 liverpool central 1
33 liverpool east 2
所以这里任何中心/主要/更大的东西都将是1,然后沿着指南针NESW将是2-5(在这个阶段不要对位置ID过于担心)
as.integer(
factor(ifelse(quux$location %in% c("main", "greater"), "central", quux$location),
levels = c("central", "north", "east", "south", "west"))
)
# [1] 1 2 4 2 4 3 1 2 3 5 1 3
您为第 12 行(利物浦、东)列出了
2
,尽管您明确表示东应该是 3
,所以我认为这是正确的。