对每个数据框应用一个函数 [英] Apply a function to each data frame

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

问题描述

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

I have 4 data frames which contain a date column, a price column and a return column.

数据 1:

Date        Price  Return
2009-01-02  100    0.2
2009-01-03  110    0.1
etc.

数据 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天全站免登陆