gpt4 book ai didi

R:在 dplyr::mutate() 中使用 min()

转载 作者:行者123 更新时间:2023-12-02 01:37:26 24 4
gpt4 key购买 nike

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

问题:如何将正确的值放入 min() 函数作为 mutate() 的一部分 - 基本上,我想将 v3 分配为v1除以v1v2中最小的一个。这不起作用:

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

我想我错过了一些非常简单的东西。

最佳答案

来自 ?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.

另一方面:

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

所以你想在这里使用pmin。对于 dplyr,一个选项 - 正如上面评论的 - 是这样的:

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

这里的一个很好的副作用是,您可以避免使用 ifelse ,而只需与逻辑向量相乘(TRUE/FALSE,然后转换为 1/0)。

关于R:在 dplyr::mutate() 中使用 min(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28070878/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com