简体   繁体   中英

How to use user defined function within `lapply`

This is just an example and this is my hypothetical data base :

date <- as.Date(c('2015-07-01','2015-07-05', '2015-07-10', '2015-07-01', '2015-07-05', '2015-07-10'))
id <- c(1,1,1,2,2,2)
a <- c('a','z','e','r','t','y')
b <- c('y','t','r','e','z','a')
price <- c(1,2,3,4,5,6)
df <- data.frame(id,date,a,b,price)

I'd like to split the data frame df by id and to apply the function fonct() to all the elements of the list but treating each element as a data frame. Something like this :

library(dplyr)
library(xts)

fonct<-function(data){
drep1<- data[1,]
drep1$a<- drep1$b
drep1$p<- 0
drep2<- data[1,]
drep2$b<- drep2$a
drep2$p<- 0
d<-rbind(data,drep1,drep2)%>% arrange(date) 
d<- as.xts(data$p, order.by=data$date)}
  1. This would work : df2 <- lapply(df,fonct(x))
  2. This would not work : df2 <- lapply(split(df, df$id),fonct(x))

The second example would not work because the elements coming out of split are not a data frame.

Don't use fonct(x) in your lapply call. Just use the function name. For example

df2 <- lapply(split(df, df$id),fonct)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM