This is my first question here on Stack Overflow, so I apologize in advance if I won't be clear enough. I searched for similar questions, but I didn't find anything (I probably didn't search enough!)
Given a data.frame (or a data.table or a tibble) consisting of four sets of points divided into two groups:
df_points <- tibble(
x = c(rnorm(10000, mean = 0), rnorm(10000, mean = 1),
rnorm(10000, mean = 0), rnorm(10000, mean = 4)),
dist = c(rep("d1", 10000), rep("d2", 10000),
rep("d1", 10000), rep("d2", 10000)),
overlap = c(rep("o1", 20000), rep("o2", 20000))
)
my goal is to apply the density function, using different values of bw, from and to for the "o1" and "o2" groups.
I would like to solve this problem in an elegant way with both a tidyverse and a R-base-data.table approach (apply family functions).
For now I have managed to do this via tidyverse:
I define a
common_densfunction which appliesdensityand returns a tibble of thexandyof the distributioncommon_dens <- function(df, Bw, lower, upper) { d <- density(df, n = 2048, bw = Bw, from = lower, to = upper) df_d <- tibble(x = d$x, y = d$y) return(df_d) }assuming that the values of upper, lower and bws are the following:
lower <- c(-5.050, -4.705) upper <- c(6.445, 9.070) bws <- c(0.1427, 0.1417)I get the desired dataframe through the following
forloop:df_dens <- NULL for (i in 1:2) { df_t <- df_points %>% filter(overlap == unique(df_points$overlap)[[i]]) %>% group_by(dist, overlap) %>% summarise(common_dens(x, bws[i], lower[i], upper[i])) df_dens <- rbind(df_dens, df_t) }
Is there any way to remove the for loop?
Is there a way to do the same with apply family functions and data.table?
Thanks for your help!