r - Apply a function to each data frame -
i have 4 data frames contain date column, price column , return column.
data.1:
date price return 2009-01-02 100 0.2 2009-01-03 110 0.1 etc.
data.2:
date price return 2009-02-02 60 0.15 2009-02-03 50 -0.1 etc.
i set loop , apply function density() each data frame, returning density values returns.
i through creating list, setting loop , using lapply() this, so
> ff <- list(data.1, data.2, data.3, data.4) > for(i in 1:length(ff){ density[[i]] <- lapply(ff, density(ff[[i]]$return))}
but doesn't work. offer me help?
thanks in advance - dani
first, should initialize density if want manual assignment.
densities <- list()
second, use density function in funny way. should specify function different in lapply. either give function , arguments after comma, or construct own custom little function in lapply call, shown below.
data.1 <- data.frame( x1 = letters[1:10], x2 = 1:10 ) data.2 <- data.frame( x1 = letters[11:20], x2 = 10:1 ) ff <- list(data.1,data.2) densities <- lapply(ff,function(i) {density(i$x2)})
this returns list automatically.
to data out of it, use list indices:
densities[[1]]$x
if named list before, use names :
names(ff) <- c("data.1","data.2") densities <- lapply(ff,function(i) {density(i$x2)}) densities[['data.1']]$x
Comments
Post a Comment