[R] force apply() to return a list
Robin Hankin
r.hankin at noc.soton.ac.uk
Mon Nov 21 09:16:39 CET 2005
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
More information about the R-help
mailing list