问题
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
Expected Output
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)
回答1:
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
Data
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)
来源:https://stackoverflow.com/questions/48023937/sorting-the-values-of-column-in-ascending-order-in-r