Dear All,

I have trouble generizising some code.

> index <- 0
> sapply(list(c(1,2,3),c(1,2),c(1)),function(x){x[max(length(x)-index,0)]})
Will yield a wished for vector like so:
[1] 3 2 1

But in this case (trying to select te second to last element in each vector 
of the list)
> index <- 1
> sapply(list(c(1,2,3),c(1,2),c(1)),function(x){x[max(length(x)-index,0)]})
I end up with 
[[1]]
[1] 2

[[2]]
[1] 1

[[3]]
numeric(0)

I would (massively) prefer something like
[1] 2 1 NA

My current implementation looks like
> index <- 1
> unlist(
>  sapply(
>   list(c(1,2,3),c(1,2),c(1)),
>   function(x){
>     value <- x[max(length(x)-index,0)]
>     if(identical(value,numeric(0))){return(NA)} else {return(value)}
>   }
>  )
> )
[1]  2  1 NA

Quite the inelegant eyesore.

Any hints on how to do this better?

Thanks, Joh

______________________________________________
R-help@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.

Reply via email to