将功能应用于每个数据框 [英] Apply a function to each data frame

查看:86
本文介绍了将功能应用于每个数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有4个数据框,其中包含一个日期列,一个价格列和一个返回列.

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.

我想建立一个循环,并将功能density()应用于每个数据帧,返回返回值的密度值.

I would like to set up a loop and apply the function density() to each data frame, returning the density values for the returns.

我将通过创建列表,建立循环并使用lapply()来完成此操作,因此

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?

预先感谢- 丹妮

推荐答案

首先,如果要进行手动分配,则应初始化密度.

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

densities <- list()

第二,您以有趣的方式使用密度功能.您应该在lapply中指定不同的功能.要么在逗号后给函数和多余的参数,要么在lapply调用中构造自己的自定义小函数,如下所示.

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

这篇关于将功能应用于每个数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆