根据R中另一列的顺序对一列进行排序 [英] Sorting a column based on the order of another column in R

查看:1056
本文介绍了根据R中另一列的顺序对一列进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的R脚本创建一个包含三列的数据框a123. a1列的三个变量分别出现在不同的位置,并具有相应的a2和a3值.

The R script below creates a data frame a123 with three columns. Column a1 has three variables occurring at different places with corresponding a2 and a3 values.

a1 = c("A", "B", "C", "A", "B", "B", "A", "C", "A", "C", "B")
a2 = c( 10, 8, 11 , 6 , 4 , 7 , 9 , 1 , 3 , 2, 7)
a3 = c( 55, 34, 33, 23, 78, 33, 123, 34, 85, 76, 74)
a123 = data.frame(a1, a2, a3)

我的需要是,我希望与a1列值相对应的a3列值基于a2值的顺序升序排列.另外,如果遇到通用的a2值,则应按升序排列相应的a3列值.例如,假设a1列中的值"A"在a2和a3中具有以下值,

My need is that I want a3 column values corresponding to a1 column values to be arranged in ascending order based on the order of a2 values. Also, if common a2 values are encountered, the corresponding a3 column values should be arranged in ascending order. For example, say value "A" in column a1 has following values in a2 and a3,

a2 = c(10, 6, 9, 3)
a3 = c(55, 23, 123, 85)

值可以是:

a3 = c(123, 23, 85, 55)

预期结果:

a1 = c("A", "B", "C", "A", "B", "B", "A", "C", "A", "C", "B")
a2 = c( 10, 8, 11, 6, 4, 7, 9, 1, 3, 2, 7)
a3 = c( 123, 78, 76, 23, 33, 34, 85, 33, 55, 34, 74)
a123 = data.frame(a1, a2, a3)

谢谢,请帮助. 注意:请尝试避免出现循环和条件,因为它们可能会减慢基于大数据的计算.

Thanks and please help. Note: Please try to avoid loops and conditions as they might slow the computation based on large data.

推荐答案

使用dplyrsortrank的解决方案.我不完全了解您的逻辑,但这可能是您正在寻找的东西.注意,我假设组Aa3中的元素是123, 55, 85, 23.

A solution using dplyr, sort, and rank. I do not fully understand your logic, but this is probably something you are looking for. Notice that I assume the elements in a3 of group A is 123, 55, 85, 23.

library(dplyr)

a123_r <- a123 %>%
  group_by(a1) %>%
  mutate(a3 = sort(a3, decreasing = TRUE)[rank(-a2, ties.method = "last")]) %>%
  ungroup() %>%
  as.data.frame()
a123_r
#    a1 a2  a3
# 1   A 10 123
# 2   B  8  78
# 3   C 11  76
# 4   A  6  55
# 5   B  4  33
# 6   B  7  34
# 7   A  9  85
# 8   C  1  33
# 9   A  3  23
# 10  C  2  34
# 11  B  7  74

这篇关于根据R中另一列的顺序对一列进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆