如何更改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 x21 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 y21 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 y21 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 x21 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
以上是 如何更改R中列表中元素的顺序? 的全部内容, 来源链接: utcz.com/z/317480.html