0

I know this question has been asked before but I"m unable to get the answers to work for me. I am trying to generate several Gaussian curves with the dpearson function from PearsonDS. A simple toy example of it working:

library(PearsonDS)
moments <- c(mean=1,variance=2,skewness=1,kurtosis=5)
dpearson(seq(-2,3,by=1),moments=moments)

So it needs a vector of x values and a list of moments 5 arguments long.

I'm wanting to generate 7 curves and first created a matrix with all my moments:

df = data.frame( 
            mean = c(-6,-4,-2,0,2,4,6),
            variance = c(1,1,1,1,1,1,1),
            skewness = c(-2, -1, -0.5, 0, 0.5, 1, 2),
            kurtosis = c(7, 3, 1, 0, 1, 3, 7))

I'd also like the curves to be staggered along x so I used a function to create different x values centered on the means of the curves:

x = Map(seq, df$mean-3, df$mean+3)

However, even if I just use one set of values for x (x[[1]]), I can't successfully get my df to input as an argument into the dpearson function. I've tried various forms of lapply and apply such as:

apply(df,1,dpearson(x[[1]],moments=df)

but I can only get it to work if I specify the first row outside of apply:

dpearson(x[[1]],moments=df[1,]

So my question is, how can I write a function that will accept each row of both x and the df as inputs for the dpearson argument? It would also be great if I could have the x vector depend on the mean values from df such as

function{
x = Map(seq, d$mean-3, d$mean+3)
Curves = dpearson(x,moments=df) # where it does row-wise calculations for both x and df
}

Thank you for your help.

aarsmith
  • 65
  • 6

1 Answers1

2

I would avoid using apply when working with data.frames. You can use Map to map over multiple lists. We can use asplit to turn your data.frames into a list of row values (see other methods). This type of strategy should work

Map(dpearson, 
  Map(seq, df$mean-3, df$mean+3), 
  moments=asplit(df, 1)
)
MrFlick
  • 195,160
  • 17
  • 277
  • 295
  • I get an error a do call error 'what' must be a function or character string – aarsmith Feb 24 '23 at 22:00
  • @aarsmith Didn't realize `moments=` wasn't the second parameter. You can name it as I've edited above. Also note your example returns an error for `dpearson(x[[3]],moments=df[3,])` – MrFlick Feb 24 '23 at 22:37