How to create a column of factorial values in data frames stored in R list?


To create a column of factorial values in data frames stored in R list, we can follow the below steps −

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

  • Then, use lapply function to create a column of factorial values in data frames stored in the list.

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(x=sample(1:9,25,replace=TRUE))
df2<-data.frame(x=sample(1:9,25,replace=TRUE))
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]]
   x
1  1
2  2
3  8
4  9
5  7
6  1
7  8
8  8
9  6
10 7
11 2
12 9
13 2
14 8
15 8
16 4
17 5
18 1
19 6
20 3
21 8
22 3
23 4
24 6
25 3

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

Create a column of factorial values

Using lapply function to create a column of factorial values in data frames df1 and df2 stored in the list called List as shown below −

df1<-data.frame(x=sample(1:9,25,replace=TRUE))
df2<-data.frame(x=sample(1:9,25,replace=TRUE))
List<-list(df1,df2)
lapply(List,function(x) {
+ x$Factorial<-factorial(x$x)
+ return(x)
+ })

Output

[[1]]
   x Factorial
1  6 720
2  4 24
3  5 120
4  3 6
5  9 362880
6  1 1
7  5 120
8  8 40320
9  6 720
10 5 120
11 3 6
12 9 362880
13 9 362880
14 1 1
15 6 720
16 4 24
17 8 40320
18 3 6
19 2 2
20 9 362880
21 8 40320
22 3 6
23 3 6
24 2 2
25 6 720
[[2]]
   x Factorial
1  8 40320
2  5 120
3  1 1
4  4 24
5  1 1
6  4 24
7  9 362880
8  7 5040
9  7 5040
10 5 120
11 2 2
12 4 24
13 8 40320
14 4 24
15 3 6
16 8 40320
17 7 5040
18 8 40320
19 1 1
20 4 24
21 9 362880
22 8 40320
23 2 2
24 4 24
25 6 720

Updated on: 10-Nov-2021

159 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements