-2

I'd like to have KDE probability on a data frame grouped by multiple columns. Tried:

d <- data %>% 
    group_by(type,culture,set) %>%
    do(density(.$obs))

Error in .density(.$obs) : could not find function ".density"

Maurits Evers
  • 49,617
  • 4
  • 47
  • 68

1 Answers1

2

You should always provide minimal reproducible sample data along with your post, so that SO respondents have something to work with. Sample data also often helps us to understand what it is you're trying to do and avoids ambiguities regarding data types.

That aside, a more canonical tidyverse approach would be to nest data and then map density to the relevant column. Following is an example based on mtcars

library(tidyverse)
res <- mtcars %>%
    group_by(gear) %>%
    nest() %>%
    mutate(dens = map(data, ~density(.x$mpg)))
res
## A tibble: 3 x 3
#   gear data               dens
#  <dbl> <list>             <list>
#1     4 <tibble [12 × 10]> <S3: density>
#2     3 <tibble [15 × 10]> <S3: density>
#3     5 <tibble [5 × 10]>  <S3: density>

Note how res$dens is a list of density objects.

Maurits Evers
  • 49,617
  • 4
  • 47
  • 68
  • it throws error now `+ + + Error in UseMethod("map") : no applicable method for 'map' applied to an object of class "c('vctrs_list_of', 'vctrs_vctr')"`, any idea why? – doctorate Apr 11 '20 at 09:19
  • @doctorate Not sure what you mean. The code I give above works just fine and results are reproducible. If this is a different issue (involving different data and code) you should post a new question including reproducible & minimal sample data and the necessary code to reproduce the error you're getting. Otherwise we will not be able to help. – Maurits Evers Apr 14 '20 at 06:50
  • 1
    sorry for bringing up this issue, but it turned out that there is a namespace conflict, `map` function was the problem from `mclust` package, the reason for this error, it was fixed by explicitly writing the `purrr:map` function name. – doctorate Apr 14 '20 at 17:19