How to change the name of data frames stored in an R list?


To change the name of data frames stored in an R list, we can follow the below steps −

  • First of all, create a list of data frames.

  • Then, use names function to change the name of data frames.

Example

Create the list of data frames

Using data.frame function to create data frames and list function to create the list of those data frames −

df1<-data.frame(x1=rpois(25,5),x2=rpois(25,3),x3=rpois(25,1))
df2<-data.frame(y1=rpois(25,5),y2=rpois(25,3),y3=rpois(25,1))
List<-list(df1,df2)
List

Output

On executing, the above script generates the below output(this output will vary on your system due to randomization) −

[[1]]
  x1 x2 x3
1  5  2 0
2  1  4 3
3  1  2 2
4  3  2 0
5  6  4 2
6  5  3 0
7  4  1 2
8  3  1 1
9  4  1 0
10 4  3 0
11 5  2 1
12 7  3 3
13 2  3 0
14 5  5 0
15 9  5 0
16 4  1 1
17 2  3 1
18 6  4 1
19 4  4 0
20 9  9 1
21 9  1 1
22 4  1 2
23 5  5 0
24 5  4 1
25 4  2 0

[[2]]
   y1 y2 y3
1  3  6  1
2  9  6  1
3  8  5  0
4  8  5  2
5  7  3  0
6  6  1  0
7  6  5  0
8  4  2  0
9  2  3  0
10 2  3  1
11 5  1  1
12 6  8  0
13 2  3  2
14 9  2  0
15 5  4  2
16 5  2  0
17 7  3  0
18 5  3  1
19 10 2  0
20 3  4  1
21 5  6  1
22 10 2  4
23 6  5  0
24 3  0  1
25 1  0  1

Change the name of data frames in list

Using names function to change the name of data frames stored in list called List as shown below −

df1<-data.frame(x1=rpois(25,5),x2=rpois(25,3),x3=rpois(25,1))
df2<-data.frame(y1=rpois(25,5),y2=rpois(25,3),y3=rpois(25,1))
List<-list(df1,df2)
names(List)<-c("X","Y")
List

Output

$X
   x1 x2 x3
1  9  3  0
2  2  5  1
3  4  2  0
4  7  5  1
5  3  5  2
6  2  2  3
7  7  2  0
8  2  1  1
9  1  2  1
10 9  4  1
11 5  3  1
12 8  6  0
13 7  3  2
14 6  2  2
15 4  5  0
16 5  1  0
17 5  3  0
18 7  1  1
19 3  5  0
20 4  3  0
21 8  1  1
22 4  0  1
23 10 0  0
24 8  4  4
25 3  6  0

$Y
   y1 y2 y3
1  5  3  1
2  5  5  2
3  5  2  1
4  2  3  1
5  3  5  3
6  3  3  0
7  3  1  0
8  6  4  2
9  8  3  0
10 3  0  1
11 6  1  0
12 4  4  0
13 5  2  0
14 4  2  1
15 9  3  2
16 7  4  1
17 5  2  2
18 6  2  2
19 3  1  0
20 4  4  1
21 3  1  0
22 3  4  3
23 7  2  1
24 1  5  4
25 8  3  0

Updated on: 09-Nov-2021

797 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements