简体   繁体   中英

Passing row as an argument to a function in R dplyr mutate

I'm writing a program that calculates the difference between an element of a dataset and the rest of elements. I'm using dplyr mutate and I need to pass the entire row as an argument to a function which calculates the difference. Using iris as a example:

#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 works, but as I use the entire row, I would like to use something like "this" or "row" instead of specifying all the columns of the row:

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

Does anyone know if this can be done?

We can do this very easily in base R by replicating the chosenElement to make the dimensions same

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

Note that mutate is for changing/transforming the values of a single column/multiple columns -> a single column. Of course, we can place other types of objects in a list . Assuming that the 'difference' should be for each column of 'elements' with that of corresponding element of 'chosenElement', the mutate is not doing that with the diff_func

Update

Based on the clarification it seems we need get the difference between the columns with the corresponding chosenElement (here we replicated) and then do the rowSums

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

purrr base组合:

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

Since (a - d) + (b - e) + (c - f) == (a + b + c) - (d + e + f) , it's just a difference between row sums of the elements and sum of chosenElements , which you can do within base R:

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

Or, in dplyr :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM