按向量 B 对命名向量 A 的值进行排序,但尽可能保持名称顺序
我有一个这样的命名向量:
my_vec <- c("Max"= "England", "Manfred"= "Germany", "Ingolf"= "Germany", "Paul"= "England", "Peter"= "Germany", "Nina"= "Italy")
我需要按另一个向量中指定的国家/地区对该向量进行排序,同时保持给定国家/地区的人员顺序与以前一样。因此,如果国家/地区的顺序是...
sort_scheme <- c("England", "Germany", "Italy")
...那么我想要的输出是:
goal_vec <- c("Max"= "England", "Paul"= "England", "Manfred"= "Germany", "Ingolf"= "Germany", "Peter"= "Germany", "Nina"= "Italy")
如您所见,所需的输出具有与 sort_scheme
中相同的国家/地区顺序(首先是英格兰,然后是德国,然后是意大利),并且在一个国家/地区内,姓名的原始顺序是相同的(对于英格兰,Max 排在第一位,然后是 Paul,依此类推)。该解决方案对于具有基本 R 的其他角色(新名称和国家)应该是灵活的。我想出的所有内容都非常麻烦。
编辑我发现这是一个
I have a named vector like that:
my_vec <- c("Max"= "England", "Manfred"= "Germany", "Ingolf"= "Germany", "Paul"= "England", "Peter"= "Germany", "Nina"= "Italy")
I need to sort this vector by countries as specified in another vector while keeping the order of the persons for a given country as before. So if the ordering of the countries is...
sort_scheme <- c("England", "Germany", "Italy")
... then my desired output is:
goal_vec <- c("Max"= "England", "Paul"= "England", "Manfred"= "Germany", "Ingolf"= "Germany", "Peter"= "Germany", "Nina"= "Italy")
As you can see the desired output has the same order of countries as in sort_scheme
(England first, then Germany, then Italy) and, inside one country the original order of names is the same (for England Max comes first then Paul, and so on). The solution should be flexible for other characters (new names and countries) with base R. All I've come up with is incredibly cumbersome.
Edit I found this being a duplicate and voted to close.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我们可以使用
order
:my_vec[order(match(my_vec, sort_scheme))]
根据 @MerijnvanTilborg - 如果需要使用向量名称进行“嵌套”排序(即OP中的情况并非如此)我们可以使用:
my_vec[order(match(my_vec, sort_scheme), names(my_vec))]
请参阅
?order
:We can use
order
:my_vec[order(match(my_vec, sort_scheme))]
As per @MerijnvanTilborg - if "nested" ordering using the vector names is required (which is not the case in the OP) we can use:
my_vec[order(match(my_vec, sort_scheme), names(my_vec))]
See
?order
:对命名值进行排序会按向量的值而不是名称对向量进行排序。假设您的 sort_scheme 按 AZ 的字母顺序排列,您可以在向量上使用
sort
。Sorting a named value sorts the vector by its values and not its names. Assuming your sort_scheme is alphabetically from A-Z you can just use
sort
on your vector.