在R中按升序对列的值进行排序
下面的脚本是一个四列的数据框.我需要一次获取一对值(a1,a2).列"a3"是这样的:如果您在跨数据时检查对说(a1,a2),那么对的值将按升序排列.如果表中存在该对的重复项,则我希望"a4"列值的排列方式与特定(a1,a2)值的对应"a3"列一样,以升序排列.说第一对(a1,a2)("A","D"),该对出现三次,并且相应的a3值按升序排列.同样,我希望基于a4值的升序排列a4值.请检查预期结果.谢谢,请提出建议.
The script below is a data frame of four columns. My need is that I want to take a pair of values(a1,a2) at a time. The column "a3" is such that if you check a pair say (a1,a2), as you span the data, the pair's value is arranged in ascending order. If there is a duplicate of the pair present in the table, I want the "a4" column values to be arranged just like the corresponding "a3" column in ascending order for the particular (a1,a2) value. Say the first (a1,a2) pair ("A","D"), the pair appears thrice and the corresponding a3 values are in asecending order. Similarly I wish to arrange the a4 values based on the order of a4 values in ascending order. Please check the expected outcome. Thanks and please suggest.
a1 = c("A","B","C","A","B","C","A","C")
a2 = c("D","E","F","D","E","E","D","F")
a3 = c(5,15,12,10,40,35,20,50)
a4 = c(100,160,66,65,130,150,80,49)
a123= data.frame(a1,a2,a3,a4)
library(dplyr)
a123_r <- a123 %>%
group_by(a1, a2) %>%
mutate(a3 = sort(a3)) %>%
ungroup()
a123_r
预期产量
a1 = c("A","B","C","A","B","C","A","C")
a2 = c("D","E","F","D","E","E","D","F")
a3 = c(5,15,12,10,40,35,20,50)
a4 = c(65,130,66,80,160,150,100,49)
a123_r <- data.frame(a1,a2,a3,a4)
为完整起见,以下是使用data.table
的答案:
For the sake of completeness, here is an answer using data.table
:
library(data.table)
cols <- c("a3", "a4")
setDT(a123)[, (cols) := lapply(.SD, sort), by = .(a1, a2), .SDcols = cols][]
a1 a2 a3 a4
1: A D 5 65
2: B E 15 130
3: C F 12 49
4: A D 10 80
5: B E 40 160
6: C E 35 150
7: A D 20 100
8: C F 50 66
数据
a1 = c("A","B","C","A","B","C","A","C")
a2 = c("D","E","F","D","E","E","D","F")
a3 = c(5,15,12,10,40,35,20,50)
a4 = c(100,160,66,65,130,150,80,49)
a123= data.frame(a1,a2,a3,a4)