0

I need to sum sequences generated by one of column. I have done it in that way:

test <- tibble::tibble(
  x = c(1,2,3)
)
test %>% dplyr::mutate(., s = plyr::aaply(x, .margins = 1, .fun = function(x_i){sum(seq(x_i))}))

Is there a cleaner way to do this? Is there some helper functions, construction which allows me to reduce this:

plyr::aaply(x, .margins = 1, .fun = function(x_i){sum(seq(x_i))})

I am looking for a generic solution, here sum and seq is only an example. Maybe the real problem is that I do want to execute function on element not all vector.

This is my real case:

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
})

I would like to do that by mutate function in a row way not vectorized way.

koralgooll
  • 392
  • 1
  • 3
  • 12

1 Answers1

5

For the specific example, it is a direct application of cumsum

test %>% 
   mutate(s = cumsum(x))

For generic cases to loop through the sequence of rows, we can use map

test %>% 
     mutate(s = map_dbl(row_number(), ~ sum(seq(.x))))
# A tibble: 3 x 2
#      x     s
#  <dbl> <dbl>
#1     1     1
#2     2     3
#3     3     6

Update

For the updated dataset, use map2, as we are using corresponding arguments in dnorm from the 'x' and 'y' columns of the dataset

test %>%     
    mutate(V1 = map2_dbl(x, y, ~ dnorm(d, mean = .x, sd = .y) %>% 
                     sum))
# A tibble: 3 x 3
#     x     y    V1
#  <dbl> <dbl> <dbl>
#1     1   0.5 1.56 
#2     2   1   0.929
#3     3   1.5 0.470
akrun
  • 874,273
  • 37
  • 540
  • 662