R:在dplyr :: mutate()中使用min() [英] R: use min() within dplyr::mutate()
问题描述
require(dplyr)
set.seed(8)
df< -
data.frame
v1 = runif(10,-1,1),
v2 = runif(10,-1,1))
问题:
如何在 min()
函数中获取正确的值作为$ $ c的一部分$ c> mutate() - 基本上,我想将 v3
分配为 v1
除以 v1
和 v2
中的最小值。
这不工作:
df< -
df%>%mutate(v3 = ifelse (v1!= 0,v1 / min(v1,v2),0))
我想我我错过了一些非常简单的东西。
从?min
:
pmax和pmin以一个或多个向量(或矩阵)为参数,
返回一个单个向量,
向量的平行'最大值(或最小值)。
另一方面:
max和min返回
中所有值的最大或最小值,其参数
所以你想在这里使用 pmin
。使用dplyr,如上所述,一个选项就是这样:
df%>%mutate(v3 =(v1! = 0)* v1 / pmin(v1,v2))
这里的好的副作用是你可以避免使用 ifelse
,只需使用逻辑向量(TRUE / FALSE,然后转换为1/0)。
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 v3
as 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.
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).
这篇关于R:在dplyr :: mutate()中使用min()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!