To create a column of absolute 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 absolute values in data frames stored in the list.
Using data.frame function to create data frames and list function to create the list of those data frames −
df1<-data.frame(x=sample(-20:10,25)) df2<-data.frame(x=sample(-20:10,25)) List<-list(df1,df2) List
On executing, the above script generates the below output(this output will vary on your system due to randomization) −
[[1]] x 1 -5 2 -19 3 -14 4 1 5 0 6 -3 7 -12 8 9 9 7 10 -13 11 -18 12 -15 13 -10 14 -17 15 -1 16 4 17 -9 18 -11 19 -6 20 -20 21 10 22 8 23 -8 24 3 25 -7 [[2]] x 1 -7 2 -16 3 10 4 -8 5 -5 6 2 7 -18 8 -6 9 -13 10 5 11 -17 12 9 13 -15 14 -9 15 8 16 -10 17 -2 18 -20 19 6 20 -4 21 -3 22 -1 23 -14 24 7 25 0
Create a column of absolute values
Using lapply function to create a column of absolute values in data frames df1 and df2 stored in the list called List as shown below −
df1<-data.frame(x=sample(-20:10,25)) df2<-data.frame(x=sample(-20:10,25)) List<-list(df1,df2) lapply(List,function(x) { + x$Absolute<-abs(x$x) + return(x) + })
[[1]] x Absolute 1 -6 6 2 3 3 3 -12 12 4 -3 3 5 -9 9 6 -1 1 7 -5 5 8 10 10 9 -4 4 10 4 4 11 -7 7 12 9 9 13 -13 13 14 -8 8 15 -11 11 16 -20 20 17 -16 16 18 -2 2 19 -18 18 20 7 7 21 -17 17 22 1 1 23 0 0 24 8 8 25 6 6 [[2]] x Absolute 1 -7 7 2 -3 3 3 -5 5 4 -1 1 5 -17 17 6 5 5 7 -13 13 8 0 0 9 -19 19 10 -2 2 11 -6 6 12 -18 18 13 3 3 14 -10 10 15 -9 9 16 6 6 17 7 7 18 -15 15 19 -4 4 20 -16 16 21 2 2 22 9 9 23 4 4 24 1 1 25 -20 20