Reputation: 1245
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?
Upvotes: 3
Views: 360
Reputation: 4505
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))
Upvotes: 0
Reputation: 887721
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
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(.)]))
Upvotes: 2
Reputation: 13319
A purrr
base
combination:
do.call(cbind,purrr::map2(elements,chosenElement,function(x,y) x-y))
Upvotes: 1