Applying a function to each data frame

I have 4 data frames that contain a date column, a price column, and a 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 would like to adjust the loop and apply the density function () to each data frame, returning density values ​​for returns.

I need to create a list, set up a loop, and use lapply () for 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 this obviously does not work. Can anyone help me?

Thanks in advance - Dani

+8
loops r
source share
2 answers

First, you must initialize the density if you want to perform this manual assignment.

 densities <- list() 

Secondly, you use the density function funny. You must specify the function in different ways. Either you provide a function and additional decimal arguments, or you create your own custom small function in a Lapply call, as 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 automatically returns a list.

To get data from it, you simply use list indices:

 densities[[1]]$x 

If you have named your list before, you can also use the names:

 names(ff) <- c("data.1","data.2") densities <- lapply(ff,function(i) {density(i$X2)}) densities[['data.1']]$x 
+10
source share

The thing with the foot is that you do not need to use for-loop. This should work:

 data.1=data.2=data.3=data.4=matrix(rnorm(30),ncol=3) ff=list(data.1,data.2,data.3,data.4) densities=lapply(ff,function(x)density(x[,3])) 

Although, undoubtedly, the best way to do this (I mean assigning a list manually).

+3
source share

All Articles