[英]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. 我想按
id
split
数据帧df
,并将函数fonct()
应用于列表的所有元素,但将每个元素都视为数据帧。 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)}
df2 <- lapply(df,fonct(x))
df2 <- lapply(df,fonct(x))
df2 <- lapply(split(df, df$id),fonct(x))
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. 第二个示例不起作用,因为
split
的元素不是数据帧。
Don't use fonct(x)
in your lapply
call. 不要在您的
lapply
调用中使用fonct(x)
。 Just use the function name. 只需使用函数名称即可。 For example
例如
df2 <- lapply(split(df, df$id),fonct)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.