The unlist solution is quite clever.

But I will note that none of the solutions offered so far succeed if the input 
is, for example,

   YH <- list(1:5, letters[1:3], 1:7)
    iuhV <- c(2,2,4)

and the desire is to return a list whose elements are of the same types as the 
input list. Which would be the sensible thing to do if the input list mixes 
types.

(Note that the output structure was not specified in the original question, nor 
was it stated whether the input list could mix types)

unlist(YH, recursive = FALSE, use.names = FALSE)[cumsum( lengths(YH)) - 
lengths(YH) + iuhV]
[1] "2" "b" "4"

However,

> lapply( 1:length(YH), function(i) { YH[[i]][iuhV[i]]})
[[1]]
[1] 2

[[2]]
[1] "b"

[[3]]
[1] 4

--
Don MacQueen
Lawrence Livermore National Laboratory
7000 East Ave., L-627
Livermore, CA 94550
925-423-1062
Lab cell 925-724-7509
 
 

On 6/18/18, 10:00 AM, "R-help on behalf of Berry, Charles" 
<r-help-boun...@r-project.org on behalf of ccbe...@ucsd.edu> wrote:

    
    
    > On Jun 18, 2018, at 4:15 AM, akshay kulkarni <akshay...@hotmail.com> 
wrote:
    > 
    > correction....I want the method without a for loop
    
    Here are two. The first is more readable, but the second is 5 times faster.
    
    mapply("[", YH, iuhV)
    
    unlist(YH, recursive = FALSE, use.names = FALSE)[cumsum( lengths(YH)) - 
lengths(YH) + iuhV]
    
    HTH,
    
    Chuck
    
    > ________________________________
    > From: akshay kulkarni <akshay...@hotmail.com>
    > Sent: Monday, June 18, 2018 4:25 PM
    > To: R help Mailing list
    > Subject: subsetting lists....
    > 
    > dear members,
    >                            I have list YH and index vector iuhV. I want 
to select iuhV[1] from YH[[1]], iuhv[2] from YH[[2]], iuhv[3] from 
YH[[3]]......iuhv[n] from YH[[n]]...
    > 
    > How to do this?
    > I searched SO and the internet but was bootless....
    > 
    > Very many thanks for your time and effort.....
    > Yours sincerely,
    > AKSHAY M KULKARNI
    > 
    >   [[alternative HTML version deleted]]
    > 
    
    ______________________________________________
    R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
    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.
    

______________________________________________
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
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