Reputation: 13
I am trying to add a column in a data.frame and have the output of that new column be the division of column 3 by column 2, here is an example:
mylist <- list( a=c(0,1,2),b=c(0,2,3),c=c(0,4,5))
this returns:
$a
[1] 0 1 2
$b
[1] 0 2 3
$c
[1] 0 4 5
I would like to return:
$a
[1] 0 1 2 2
$b
[1] 0 2 3 1.5
$c
[1] 0 4 5 1.25
Please help
Upvotes: 1
Views: 373
Reputation: 39154
We can use the purrr
package.
library(purrr)
map(mylist, ~c(., .[3]/.[2]))
$a
[1] 0 1 2 2
$b
[1] 0.0 2.0 3.0 1.5
$c
[1] 0.00 4.00 5.00 1.25
Upvotes: 1
Reputation: 887118
We can loop through the list
with lapply
, divide the 3rd element by the 2nd and concatenate with the original vector
lapply(mylist, function(x) c(x, x[3]/x[2]))
Upvotes: 1