下面的脚本是四列的数据框。我的需要是我想一次取一对值(a1,a2)。列“a3”是这样的,如果您检查一对说(a1,a2),当您跨越数据时,该对的值按升序排列。如果表中存在对的副本,我希望“a4”列值的排列方式与特定(a1,a2)值的升序相对应的“a3”列相同。假设第一个(a1,a2)对(“A”,“D”),该对出现三次,相应的a3值按升序排列。类似地,我希望根据a4值的顺序按升序排列a4值。请检查预期结果。谢谢,请提出建议。
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)
答案 0 :(得分:0)
为了完整起见,这是使用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)