Featured post
r - Density Value for each Return -
i have dataframe "foo" looking this
date return 1998-01-01 0.02 1998-01-02 0.04 1998-01-03 -0.02 1998-01-04 -0.01 1998-01-05 0.02 ... 1998-02-01 0.1 1998-02-02 -0.2 1998-02-03 -0.1 etc.
i add dataframe new column showing me density value of corresponding return. tried:
foo$density <- for(i in 1:length(foo$return)) density(foo$return, = foo$return[i], = foo$return[i], n = 1)$y
but didn't work. have difficulty applying "function" each row. maybe there way it, not using density()?
what extract fitted density values density() returns in foo. if plot(density(foo$return)) gives me curve, have density values attached returns.
@joris:
foo$density <- density(foo$return, n=nrow(foo$return))$y
calculates something, seems return wrong density values.
thank helping me out! dani
on second thought, forget density function, realized wanted do. density functions return grid, don't give evaluation in exact points. if want that, can eg use sm
package:
require(sm) foo <- data.frame(return=rpois(100,5)) foo$density <- sm.density(foo$return,eval.points=foo$return)$estimate # plot id <- order(foo$return) hist(foo$return,freq=f) lines(foo$return[id],foo$density[id],col="red")
if number of different values not big, can use ave() :
foo$counts <- ave(foo$return,foo$return,fun=length)
if purpose plot density function, there's no need calculate did. use
plot(density(foo$return))
or, add histogram underneath (mind option freq=f
)
hist(foo$return,freq=f) lines(density(foo$return),col="red")
- Get link
- X
- Other Apps
Comments
Post a Comment