use pmap() to calculate row means of several columns

非 Y 不嫁゛ 提交于 2019-12-06 08:38:04

We need to concatenate the argument for the x parameter in mean as

x: An R object. Currently there are methods for numeric/logical vectors and date, date-time and time interval objects. Complex vectors are allowed for ‘trim = 0’, only.

So, if we pass argument like x1, x2, x3, etc, it will be going into the ... parameter based on the usage

mean(x, ...)

For e.g.

mean(5, 8) # x is 5
#[1] 5 
mean(8, 5) # x is 8
#[1] 8
mean(c(5, 8)) # x is a vector with 2 values
#[1] 6.5

In the rowwise function, the OP concatenated the elements to a single vector while with pmap it is left as such for mean to apply on the first argument

out1 <- mtcars %>% 
         mutate(comp_var = pmap_dbl(list(vs, am, cyl), ~mean(c(...)))) %>% 
         dplyr::select(comp_var, vs, am, cyl)

-checking with the rowwise output

out2 <- mtcars %>% 
         rowwise() %>% 
         mutate(comp_var = mean(c(vs, am, cyl))) %>% 
         dplyr::select(comp_var, vs, am, cyl) %>% 
         ungroup()

all.equal(out1, out2, check.attributes = FALSE)
#[1] TRUE
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!