Ezequiel Garay
Ezequiel Garay

Reputation: 37

Adding new variable to each element of a list of data.frames

I have a list of data frames ( C ). I want to add a new variable "d" to each data frame, wich'd be the sum of "a" and "b". Here's a short example.

A<-data.frame(1:10, 101:110, 201:210)
colnames(A)=c("a","b", "c")

B<-data.frame(11:20, 111:120, 211:220)
colnames(B)=c("a","b", "c")

C<-list(A, B)

I've tried this, but i think there may be something simpler, specially considering the last part of the line ( value= (("["(C[[x]][1]))) + ("["(C[[x]][2])) )

lapply(seq(C), function(x) "[[<-" (C[[x]], 3, value= (("["(C[[x]][1]))) + ("["(C[[x]][2])))

Any ideas? And BTW, how can i choose the name of the variable created? Thanx in advance

Upvotes: 2

Views: 1758

Answers (2)

David Arenburg
David Arenburg

Reputation: 92300

Or using cbind

C <- lapply(C, function(x) cbind(x, d = x[["a"]] + x[["b"]]))

Or using rowSums

C <- lapply(C, function(x) cbind(x, d = rowSums(x[1:2])))

Upvotes: 3

Thomas
Thomas

Reputation: 44565

This should be easy using within:

out <- lapply(C, function(x) within(x, d <- a + b))

Here's the result:

> str(out)
List of 2
 $ :'data.frame':       10 obs. of  4 variables:
  ..$ a: int [1:10] 1 2 3 4 5 6 7 8 9 10
  ..$ b: int [1:10] 101 102 103 104 105 106 107 108 109 110
  ..$ c: int [1:10] 201 202 203 204 205 206 207 208 209 210
  ..$ d: int [1:10] 102 104 106 108 110 112 114 116 118 120
 $ :'data.frame':       10 obs. of  4 variables:
  ..$ a: int [1:10] 11 12 13 14 15 16 17 18 19 20
  ..$ b: int [1:10] 111 112 113 114 115 116 117 118 119 120
  ..$ c: int [1:10] 211 212 213 214 215 216 217 218 219 220
  ..$ d: int [1:10] 122 124 126 128 130 132 134 136 138 140

You could, then, store out as C (i.e., C <- out) to replace the original list. I just use out here to show you what is going on.

Upvotes: 2

Related Questions