set.seed(0)
Temp <- data.frame(year=rep(1:3,each=4),V1=floor(rnorm(12)*2),V2=floor(rnorm(12)*2))
year V1 V2
1 1 2 -3
2 1 -1 -1
3 1 2 -1
4 1 2 -1
5 2 0 0
6 2 -4 -2
7 2 -2 0
8 2 -1 -3
9 3 -1 -1
10 3 4 0
11 3 1 0
12 3 -2 1
我想每個年度內獨立重新排序V1和V2。我可以用10行來完成,但我相信必須有更美麗的方式才能做到。
所需的輸出:
year V1 V2
1 1 -1 -3
2 1 2 -1
3 1 2 -1
4 1 2 -1
5 2 -4 -3
6 2 -2 -2
7 2 -1 0
8 2 0 0
9 3 -2 -1
10 3 -1 0
11 3 1 0
12 3 4 1
對於品種,一個基本的R選項是'Reduce(rbind,lapply(split(Temp,Temp $ year ),功能on(x)data.frame(lapply(x,sort))))'。這使用了一個嵌套循環(帶有'lapply')。 – lmo