0

I would like to do the same what I have done here by mutate function not by ddplyr one. Is it possible to perform not vectorized operation here somehow?

test <- tibble::tibble(
  x = c(1,2,3),
  y = c(0.5,1,1.5)
)
d <- c(1.23, 0.99, 2.18)

test %>% mutate(., s = (function(x, y) {
  dn <- dnorm(x = d, mean = x, sd = y)
  s <- sum(dn)
  s
})(x,y))

test %>% plyr::ddply(., c("x","y"), .fun = function(row) {
  dn <- dnorm(x = d, mean = row$x, sd = row$y)
  s <- sum(dn)
  s
})
koralgooll
  • 392
  • 1
  • 3
  • 12
  • `test %>% rowwise() %>% mutate(...)` is the ticket to get a rowwise grouping for operations – Nate Jan 09 '19 at 18:27

1 Answers1

0

A popular method is using the dplyr function: rowwise().

library(tidyverse)

test <- tibble::tibble(
  x = c(1,2,3),
  y = c(0.5,1,1.5)
)
d <- c(1.23, 0.99, 2.18)

test %>% 
  rowwise() %>%                                # prior to mutate specify calculate rowwise
  mutate(., s = (function(x, y) {
    dn <- dnorm(x = d, mean = x, sd = y)
    s <- sum(dn)
    s})(x,y))

This yields the following result:

# A tibble: 3 x 3
      x     y     s
  <dbl> <dbl> <dbl>
1     1   0.5 1.56 
2     2   1   0.929
3     3   1.5 0.470
OTStats
  • 1,820
  • 1
  • 13
  • 22
  • Unfortunately it gives me the wrong answer. # A tibble: 3 x 3 x y s * 1 1 0.5 1.19 2 2 1 1.19 3 3 1.5 1.19 Should be: x y V1 1 1 0.5 1.5647681 2 2 1.0 0.9286773 3 3 1.5 0.4699930 – koralgooll Jan 09 '19 at 18:48
  • 1
    The numbers are the same, they are just rounded to two decimal values. – OTStats Jan 09 '19 at 18:52
  • If you run code with ddply as result you have 1.5647681, 0.9286773, 1.5 0.4699930. This is what I have expected from code. It could be even rounded. :) Solution is map() function probably. – koralgooll Jan 09 '19 at 19:00
  • Running the code I have above yield the rounded result you desire. Are you not getting this same result? I don't understand how to help. – OTStats Jan 09 '19 at 19:08
  • 1
    The number of decimal places shown in console printout depends on global options you may have set, as well as the object type that `print` is being called on. If there's a discrepancy in the number of places printed, check the actual values stored, not just what's printed out – camille Jan 09 '19 at 19:44