dividing columns in a list in R

心不动则不痛 提交于 2021-02-10 22:18:07

问题


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


回答1:


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]))



回答2:


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


来源:https://stackoverflow.com/questions/46712423/dividing-columns-in-a-list-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!