Hi All
I have a dataframe:
myframe<-data.frame(ID=c("first","second"),x=c(1,2),y=c(3,4))
And I have a function myfun:
myfun<-function(x,y) x+y
I would like to write a function myfun2 that takes myframe and myfun
as parameters and returns a list as below:
mylist
$first
[1] 4
$second
[2] 6
Could you please help me with this? Doesn't seem like the "apply"
family of functions were intended for this case.
Small typo in dataframe representation. It should have been the below one. Apologies. mylist $first [1] 4 $second [1] 6 On Mon, Jul 2, 2012 at 7:02 AM, Onur Uncu <onuruncu at gmail.com> wrote:> Hi All > > I have a dataframe: > > myframe<-data.frame(ID=c("first","second"),x=c(1,2),y=c(3,4)) > > And I have a function myfun: > > myfun<-function(x,y) x+y > > I would like to write a function myfun2 that takes myframe and myfun > as parameters and returns a list as below: > > mylist > $first > [1] 4 > > $second > [2] 6 > > Could you please help me with this? Doesn't seem like the "apply" > family of functions were intended for this case.
Hello,
Try
myfun2 <- function(DF, FUN){
x <- lapply(as.data.frame(t(DF[-1])), function(x) FUN(x[1], x[2]))
names(x) <- levels(DF[[1]])[ DF[[1]] ]
x
}
myfun2(myframe, myfun)
Hope this helps,
Rui Barradas
Em 02-07-2012 07:02, Onur Uncu escreveu:> Hi All
>
> I have a dataframe:
>
>
myframe<-data.frame(ID=c("first","second"),x=c(1,2),y=c(3,4))
>
> And I have a function myfun:
>
> myfun<-function(x,y) x+y
>
> I would like to write a function myfun2 that takes myframe and myfun
> as parameters and returns a list as below:
>
> mylist
> $first
> [1] 4
>
> $second
> [2] 6
>
> Could you please help me with this? Doesn't seem like the
"apply"
> family of functions were intended for this case.
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>