
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Create Total Column in Data Frames Stored in R List
To create a column of total 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 total 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=rpois(25,5),y=rpois(25,3),z=rpois(25,1)) df2<-data.frame(x=rpois(25,1),y=rpois(25,10),z=rpois(25,5)) 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 y z 1 5 2 1 2 4 2 0 3 4 3 0 4 3 1 0 5 6 3 1 6 6 4 1 7 5 2 1 8 4 5 0 9 9 4 1 10 5 2 0 11 7 2 0 12 4 2 1 13 4 2 1 14 9 1 1 15 4 0 1 16 10 5 1 17 6 1 1 18 4 1 1 19 4 1 0 20 5 1 2 21 8 4 0 22 6 0 0 23 3 4 0 24 5 1 0 25 4 2 1 [[2]] x y z 1 2 4 8 2 1 15 5 3 2 11 4 4 0 10 3 5 2 14 10 6 1 12 2 7 0 13 2 8 0 12 4 9 1 17 4 10 2 16 9 11 1 12 7 12 3 6 6 13 2 9 5 14 0 13 4 15 1 13 5 16 1 7 8 17 2 15 7 18 0 11 11 19 0 10 4 20 0 15 6 21 2 8 6 22 2 13 5 23 0 14 1 24 0 9 5 25 1 11 7
Create a column of total in data frames stored in the list
Using lapply function to create a column of total in data frames df1 and df2 stored in the list called List as shown below −
df1<-data.frame(x=rpois(25,5),y=rpois(25,3),z=rpois(25,1)) df2<-data.frame(x=rpois(25,1),y=rpois(25,10),z=rpois(25,5)) List<-list(df1,df2) lapply(List,function(x) { + x$Total<-x$x+x$y+x$z + return(x) + })
Output
[[1]] x y z Total 1 3 3 0 6 2 5 0 1 6 3 4 3 2 9 4 3 5 1 9 5 6 7 1 14 6 6 4 2 12 7 5 0 0 5 8 5 4 2 11 9 5 2 1 8 10 3 5 1 9 11 3 1 0 4 12 4 8 1 13 13 8 4 0 12 14 3 2 1 6 15 7 2 4 13 16 4 1 2 7 17 2 1 0 3 18 3 2 2 7 19 8 3 3 14 20 7 3 4 14 21 9 5 1 15 22 3 3 1 7 23 2 1 1 4 24 3 2 0 5 25 5 6 2 13 [[2]] x y z Total 1 0 12 6 18 2 0 19 5 24 3 5 13 6 24 4 0 8 6 14 5 0 12 5 17 6 1 10 3 14 7 0 10 4 14 8 1 14 4 19 9 1 5 7 13 10 0 5 4 9 11 1 14 6 21 12 0 6 4 10 13 0 6 4 10 14 0 5 3 8 15 1 12 7 20 16 2 4 8 14 17 0 14 5 19 18 2 8 9 19 19 1 9 4 14 20 1 11 1 13 21 0 11 5 16 22 4 11 7 22 23 0 11 6 17 24 2 9 6 17 25 0 10 5 15
Advertisements