wtrs
wtrs

Reputation: 329

R Subtracting columns within a list

I'd like to subtract specific columns within a list. I'm still learning how to properly use the apply functions. For example, given

> b <- list(data.frame(12:16, 3*2:6), data.frame(10:14, 2*1:5))
> b

[[1]]
  X12.16 X3...2.6
1     12        6
2     13        9
3     14       12
4     15       15
5     16       18

[[2]]
  X10.14 X2...1.5
1     10        2
2     11        4
3     12        6
4     13        8
5     14       10

I'd like some function x so that I get

> x(b)

[[1]]
  X12.16 X3...2.6  <newcol>
1     12        6         6
2     13        9         4
3     14       12         2
4     15       15         0
5     16       18        -2

[[2]]
  X10.14 X2...1.5  <newcol>
1     10        2         8
2     11        4         7
3     12        6         6
4     13        8         5
5     14       10         4

Thanks in advance.

Upvotes: 1

Views: 738

Answers (3)

acylam
acylam

Reputation: 18661

with dplyr:

library(dplyr)
lapply(b, function(x) x %>% mutate(new_col = .[[1]]-.[[2]]))

Result:

[[1]]
  X12.16 X3...2.6 new_col
1     12        6       6
2     13        9       4
3     14       12       2
4     15       15       0
5     16       18      -2

[[2]]
  X10.14 X2...1.5 new_col
1     10        2       8
2     11        4       7
3     12        6       6
4     13        8       5
5     14       10       4

Upvotes: 0

Brad Cannell
Brad Cannell

Reputation: 3200

Here is a solution:

lapply(b, function(x) {
  x[, 3] <- x[, 1] - x[, 2]
  x
})

[[1]]
  X12.16 X3...2.6 V3
1     12        6  6
2     13        9  4
3     14       12  2
4     15       15  0
5     16       18 -2

[[2]]
  X10.14 X2...1.5 V3
1     10        2  8
2     11        4  7
3     12        6  6
4     13        8  5
5     14       10  4

Upvotes: 1

MrFlick
MrFlick

Reputation: 206197

If your data.frames had nice and consistent names, you could use transform with lapply

b <- list(data.frame(a=12:16, b=3*2:6), data.frame(a=10:14, b=2*1:5))
lapply(b, transform, c=a-b)

Upvotes: 4

Related Questions