开发者

Apply a function to each data frame

开发者 https://www.devze.com 2023-02-06 08:58 出处:网络
I have 4 data frames which contain a date column, a price column and a return column. data.1: DatePriceReturn

I have 4 data frames which 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 set up a loop and apply the function density() to each data frame, returning the density values for the returns.

I through about creating a list, setting up a loop and using lapply() to do 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 doesn't work. Could somebody offer me some help?

Thanks in advance - Da开发者_如何学Cni


First, you should initialize density if you want to do that manual assignment.

densities <- list()

Second, you use the density function in a funny way. You should specify the function different in your lapply. Either you give the function and the extra arguments after the comma, or you construct your own custom little function in the 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 returns a list automatically.

To get the data out of it, you simply use the list indices:

densities[[1]]$x

If you named your list before, you could use the names as well :

names(ff) <- c("data.1","data.2")

densities <- lapply(ff,function(i) {density(i$X2)})
densities[['data.1']]$x


The thing with lapply is that you don't need to use a 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 there is undoubtedly a better way to do this (I mean the manual assignment of the list).

0

精彩评论

暂无评论...
验证码 换一张
取 消