user1987607
user1987607

Reputation: 2157

R - list of dataframes - how to add columns

I have a list of dataframes (my.list)

d1 <- data.frame(ref = c(1, 2, 3), y2 = c(4, 5, 6), y3 = c(7, 8, 9), y4 = c(10, 11, 12))
d2 <- data.frame(ref = c(3, 2, 1), y2 = c(6, 5, 4), y3 = c(9, 8, 1))
my.list <- list(d1, d2)

d1
    ref y2 y3 y4
  1   1  4  7 10
  2   2  5  8 11
  3   3  6  9 12

Now I want to add some columns with absolute difference values to each of the dataframes in this list. I would use the following for loop to do this for dataframe d1

for (i in names(d1)[2:length(names(d1))]){
   d1[[paste(i, 'abs_diff', sep="_")]] <- abs(d1[,i]-d1[,2])
}

d1 then looks like this:

    ref y2 y3 y4 y2_abs_diff y3_abs_diff y4_abs_diff
  1   1  4  7 10           0           3           6
  2   2  5  8 11           0           3           6
  3   3  6  9 12           0           3           6

But how can I now do this in one shot for all dataframes of my.list? I know I should be using 'lapply' for this, but I can't get it to work.

Upvotes: 2

Views: 33

Answers (1)

akrun
akrun

Reputation: 887128

Wee can use lapply to loop over the list and create the new columns by assignment

my.list1 <- lapply(my.list, function(x) {
    x[paste0(names(x)[2:length(x)], "abs_diff")] <- abs(x[-1] - x[,2])
    x
 })
my.list1
#[[1]]
#  ref y2 y3 y4 y2abs_diff y3abs_diff y4abs_diff
#1   1  4  7 10          0          3          6
#2   2  5  8 11          0          3          6
#3   3  6  9 12          0          3          6

#[[2]]
#  ref y2 y3 y2abs_diff y3abs_diff
#1   3  6  9          0          3
#2   2  5  8          0          3
#3   1  4  1          0          3

NOTE: When there is a single column to take the difference, due to recycling it will recycle the values to do the operation in each of the columns. Otherwise, we can either make the dimensions same by replicating the column or loop (as in the OP's post)

Upvotes: 1

Related Questions