如何在 R 中更改列表中元素的顺序?
R 中的列表可包含多种类型的元素,如向量、数据框、矩阵等。有时候,这些元素的顺序很重要,尤其是在我们拥有大型元素的情况下,因为很难查看列表中的大型元素。这种排序可以通过单方括号和操作符 c 来完成,如下例所示。
示例
List1<-list(df1<-data.frame(x1=rnorm(20),x2=rnorm(20)),df2<-data.frame(y1=rpois(20,2),y2=rpois(20,6))) names(List1)<-c("df1","df2") List1
$df1
输出
x1 x2 1 1.16664910 -0.12690835 2 -0.02385061 0.93010444 3 -0.73161055 -0.37920223 4 -0.17374218 1.74496001 5 -0.52846135 -0.54911936 6 0.15400858 0.26907145 7 0.62521370 -0.26914570 8 -1.29781529 -0.17368829 9 0.58040525 -0.69834218 10 0.73182782 -0.32848811 11 0.68748989 -0.43500960 12 0.18038886 -1.43329773 13 0.13023523 0.67122340 14 1.06490726 -0.50004983 15 1.44445206 -0.03914249 16 -1.30134077 0.16116851 17 1.17845705 0.10204926 18 0.06419740 1.28705524 19 0.21390196 0.41047054 20 -2.02748272 -1.03792946
示例
$df2
输出
y1 y2 1 1 8 2 3 8 3 5 9 4 0 7 5 3 4 6 1 3 7 2 10 8 0 6 9 1 5 10 1 4 11 2 6 12 0 10 13 2 14 14 3 8 15 5 14 16 2 2 17 0 9 18 1 6 19 1 7 20 4 8
示例
List1<-List1[c("df2","df1")] List1
$df2
输出
y1 y2 1 1 8 2 3 8 3 5 9 4 0 7 5 3 4 6 1 3 7 2 10 8 0 6 9 1 5 10 1 4 11 2 6 12 0 10 13 2 14 14 3 8 15 5 14 16 2 2 17 0 9 18 1 6 19 1 7 20 4 8
示例
$df1
输出
x1 x2 1 1.16664910 -0.12690835 2 -0.02385061 0.93010444 3 -0.73161055 -0.37920223 4 -0.17374218 1.74496001 5 -0.52846135 -0.54911936 6 0.15400858 0.26907145 7 0.62521370 -0.26914570 8 -1.29781529 -0.17368829 9 0.58040525 -0.69834218 10 0.73182782 -0.32848811 11 0.68748989 -0.43500960 12 0.18038886 -1.43329773 13 0.13023523 0.67122340 14 1.06490726 -0.50004983 15 1.44445206 -0.03914249 16 -1.30134077 0.16116851 17 1.17845705 0.10204926 18 0.06419740 1.28705524 19 0.21390196 0.41047054 20 -2.02748272 -1.03792946
示例
List2<-list(M1<-matrix(1:25,ncol=5),M2<-matrix(26:50,ncol=5)) names(List2)<-c("M1","M2") List2
输出
$M1 [,1] [,2] [,3] [,4] [,5] [1,] 1 6 11 16 21 [2,] 2 7 12 17 22 [3,] 3 8 13 18 23 [4,] 4 9 14 19 24 [5,] 5 10 15 20 25 $M2 [,1] [,2] [,3] [,4] [,5] [1,] 26 31 36 41 46 [2,] 27 32 37 42 47 [3,] 28 33 38 43 48 [4,] 29 34 39 44 49 [5,] 30 35 40 45 50
示例
List2<-List2[c("M2","M1")] List2
输出
$M2 [,1] [,2] [,3] [,4] [,5] [1,] 26 31 36 41 46 [2,] 27 32 37 42 47 [3,] 28 33 38 43 48 [4,] 29 34 39 44 49 [5,] 30 35 40 45 50 $M1 [,1] [,2] [,3] [,4] [,5] [1,] 1 6 11 16 21 [2,] 2 7 12 17 22 [3,] 3 8 13 18 23 [4,] 4 9 14 19 24 [5,] 5 10 15 20 25
广告