【问题标题】:Passing row as an argument to a function in R dplyr mutate将行作为参数传递给 R dplyr mutate 中的函数
【发布时间】:2019-05-11 17:15:50
【问题描述】:

我正在编写一个程序来计算数据集的一个元素与其余元素之间的差异。我正在使用 dplyr mutate,我需要将整行作为参数传递给计算差异的函数。以鸢尾花为例:

#Difference function
diff_func <- function (e1, e2) {
  return(sum(e1-e2))
}

chosenElement <- iris[1,1:4] # Chosen element
elements <- iris[10:50,1:4] # Elements to compare to

elements %>% 
  rowwise() %>% 
  mutate(difference=diff_func(chosenElement, c(Petal.Width, Petal.Length, Sepal.Width, Sepal.Length)))

这可行,但是当我使用整行时,我想使用“this”或“row”之类的东西,而不是指定行的所有列:

elements %>% 
  rowwise() %>% 
  mutate(difference=diff_func(chosenElement, row))

有谁知道这是否可以做到?

【问题讨论】:

    标签: r dplyr


    【解决方案1】:

    我们可以在base R 中非常轻松地做到这一点,方法是复制 selectedElement 以使尺寸相同

    elementsNew <- elements - chosenElement[col(elements)]
    

    请注意,mutate 用于更改/转换单列/多列的值 -> 单列。当然,我们可以将其他类型的对象放在list 中。假设'差异'应该是'元素'的每一列与'chosenElement'的相应元素的'差异',mutatediff_func 没有这样做

    更新

    根据澄清,我们似乎需要获取具有相应选择元素的列之间的差异(这里我们复制了),然后执行rowSums

    elements %>%
            mutate(difference = rowSums(. - chosenElement[col(.)]))
    

    【讨论】:

    • “差异”是整行的分数。例如:elements[1,] is: 4.9 3.1 1.5 0.1 selectedElement is: 5.1 3.5 1.4 0.2 它们的值之间的差异(chosenElement - elements[1,])是:0.2 0.4 -0.1 0.1 所以,我想要的是添加包含这些值总和的额外列: 0.2 + 0.4 -0.1 + 0.1 = 0.6: 4.9 3.1 1.5 0.1 0.600
    • @AlfonsoJiménez 我更新了帖子。你能检查一下这是不是你想要的吗
    【解决方案2】:

    purrrbase 组合:

    do.call(cbind,purrr::map2(elements,chosenElement,function(x,y) x-y))
    

    【讨论】:

      【解决方案3】:

      由于(a - d) + (b - e) + (c - f) == (a + b + c) - (d + e + f),这只是elements 的行总和与chosenElements 的总和之间的差异,您可以在基数 R 中执行此操作:

      elements$dfrnce <- rowSums(elements) - sum(chosenElement)
      

      或者,在dplyr

      elements %>%
        mutate(dfrnce = rowSums(.) - sum(chosenElement))
      

      【讨论】:

        猜你喜欢
        • 2018-04-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-07-23
        • 1970-01-01
        • 2015-03-14
        • 1970-01-01
        相关资源
        最近更新 更多