Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
286 views
in Technique[技术] by (71.8m points)

r - Apply a function to each data frame

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 - Dani

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...