Turn list of lists into specific length in R

How can I create a list of 3 lists with specific length 20,30,40 to get last 20 vectors of data as list1, last 30 vectors of data as list2, last 40 vectors of data as list3

turn

data <- seq(1,100,1)
length.y <- c(20,30,40)

into

y[[1]]=seq(81,100,1)
y[[2]]=seq(71,100,1)
y[[3]]=seq(61,100,1)

I can use a for loop or create a function like this

y <- rep(list(0),3)
for(i in 1:3){
    y[[i]] <- data[(length(data)-length.y[i]+1):length(data)]
}

My data is way complicate then this, so is there an easier way to get the same result? (using lapply for example)

2 answers

  • answered 2021-04-08 04:39 Ronak Shah

    Using tail as already suggested in comments is an easy way. You can also turn your for loop code to lapply as :

    n <- length(data)
    lapply(length.y, function(x) data[(n-x + 1):n])
    
    #[[1]]
    # [1]  81  82  83  84  85  86  87  88  89  90  91  92  93  94  95  96  97  98
    #[19]  99 100
    
    #[[2]]
    # [1]  71  72  73  74  75  76  77  78  79  80  81  82  83  84  85  86  87  88
    #[19]  89  90  91  92  93  94  95  96  97  98  99 100
    
    #[[3]]
    # [1]  61  62  63  64  65  66  67  68  69  70  71  72  73  74  75  76  77  78
    #[19]  79  80  81  82  83  84  85  86  87  88  89  90  91  92  93  94  95  96
    #[37]  97  98  99 100
    

  • answered 2021-04-08 05:23 AnilGoyal

    using purrr::map

    map(length.y, ~ data[-c(1:(length(data) - .x))])
    
    [[1]]
     [1]  81  82  83  84  85  86  87  88  89  90  91  92  93  94  95  96  97  98  99 100
    
    [[2]]
     [1]  71  72  73  74  75  76  77  78  79  80  81  82  83  84  85  86  87  88  89  90  91  92  93  94  95  96  97  98  99 100
    
    [[3]]
     [1]  61  62  63  64  65  66  67  68  69  70  71  72  73  74  75  76  77  78  79  80  81  82  83  84  85  86  87  88  89  90  91  92  93  94
    [35]  95  96  97  98  99 100