[R] function
Sarah Goslee
sarah.goslee at gmail.com
Wed May 12 19:34:38 CEST 2010
I missed the original query, but here am replying to the respondent.
On Wed, May 12, 2010 at 1:28 PM, Daniel Malter <daniel at umd.edu> wrote:
>
> There is too little information to answer your question definitively.
>
> However, an obvious reason is that you want to apply the function over
> columns of a data.frame, which is done with apply(), but you try to apply
> the function over elements of a list using lapply(). A list is not a
> data.frame and vice versa, which would be a good reason for your function to
> fail.
Ah, but a dataframe is a list.
To use your example:
> data=data.frame(y=rnorm(100),x=rnorm(100),e=rnorm(100)) # calling your data "data" is a bad idea!
> typeof(data)
[1] "list"
> is.data.frame(data)
[1] TRUE
> is.list(data)
[1] TRUE
> The below example works:
>
> data=data.frame(y=rnorm(100),x=rnorm(100),e=rnorm(100))
>
> f=function(x){quantile(x,probs=0.25)}
>
> apply(data,2,f)
And because a dataframe is a list, so does lapply!
> f=function(x){quantile(x,probs=0.25)}
>
> apply(data,2,f)
y x e
-0.7412884 -0.6666245 -0.9627692
> lapply(data, f)
$y
25%
-0.7412884
$x
25%
-0.6666245
$e
25%
-0.9627692
R: just when you think you've got a handle on it, you don't.
Sarah
--
Sarah Goslee
http://www.stringpage.com
More information about the R-help
mailing list