R: use min() within dplyr::mutate()

 ̄綄美尐妖づ 提交于 2019-12-08 14:42:17

问题


require(plyr)
require(dplyr)    
set.seed(8)
    df <- 
      data.frame(
        v1 = runif(10, -1,1),
        v2 = runif(10, -1,1))

The problem: How can I get the correct values into the min() function as part of mutate()- basically, I would like to assign v3as v1 divided with the smallest of v1 and v2. This doesnt work:

  df <- 
         df %>% mutate(v3=ifelse(v1 !=0, v1/min(v1,v2), 0))

I guess I am missing something really simple.


回答1:


From the help page on ?min:

pmax and pmin take one or more vectors (or matrices) as arguments and return a single vector giving the ‘parallel’ maxima (or minima) of the vectors.

On the other hand:

max and min return the maximum or minimum of all the values present in their arguments

So you want to use pmin here. With dplyr, one option - as commented above - is like this:

df %>% mutate(v3 = (v1 != 0) * v1/pmin(v1,v2))

Nice side effect here is that you can avoid using ifelse and just mulitply with the logical vector (TRUE / FALSE which is then converted to 1 / 0).



来源:https://stackoverflow.com/questions/28070878/r-use-min-within-dplyrmutate

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