a solution is the following
f <- function(x){list(1:max(x[1], 4))}
a2 <- cbind(1:3, 3:1)
out <- lapply(apply(a2, 1, f), "[[", 1)
I hope it helps.
Best,
Dimitris
----
Dimitris Rizopoulos
Ph.D. Student
Biostatistical Centre
School of Public Health
Catholic University of Leuven
Address: Kapucijnenvoer 35, Leuven, Belgium
Tel: +32/(0)16/336899
Fax: +32/(0)16/337015
Web: http://www.med.kuleuven.be/biostat/
http://www.student.kuleuven.be/~m0390867/dimitris.htm
----- Original Message -----
From: "Robin Hankin" <r.hankin at noc.soton.ac.uk>
To: "RHelp" <r-help at stat.math.ethz.ch>
Sent: Monday, November 21, 2005 9:16 AM
Subject: [R] force apply() to return a list
>
> Hi
>
> I have a function f() that I want to apply() to a matrix. I want
> the
> answer to be a list.
>
> However, sometimes all the vectors returned by f() are the same
> length
> and apply() returns a matrix. I do not want this.
>
> Hi
>
> How do I force apply() to consistently return a list?
> Toy example follows.
>
> R> f <- function(x){1:max(x[1],4)}
> R> a1 <- cbind(1:5,5:1)
> R> apply(a1,1,f)
> [[1]]
> [1] 1 2 3 4
>
> [[2]]
> [1] 1 2 3 4
>
> [[3]]
> [1] 1 2 3 4
>
> [[4]]
> [1] 1 2 3 4
>
> [[5]]
> [1] 1 2 3 4 5
>
> list returned: desired behaviour. Now try the
> same but with a different matrix from a1:
>
>
> R> a2 <- cbind(1:3,3:1)
> R> apply(a2,1,f)
> [,1] [,2] [,3]
> [1,] 1 1 1
> [2,] 2 2 2
> [3,] 3 3 3
> [4,] 4 4 4
>
>
> matrix returned: this is undesired behaviour (in my application, I
> pass the list to do.call()). How do I force apply() to behave
> consistently and return a list, irrespectively of the length of
> vectors returned by f()?
>
>
>
> --
> Robin Hankin
> Uncertainty Analyst
> National Oceanography Centre, Southampton
> European Way, Southampton SO14 3ZH, UK
> tel 023-8059-7743
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide!
> http://www.R-project.org/posting-guide.html
>
Disclaimer: http://www.kuleuven.be/cwis/email_disclaimer.htm