lapply function

Hi,

I have a probably simple problem but I can't solve it alone.
I have a list of numbers let's assume it is

nb <- c(2,5,3)

I want to create a list of concatenated zeros using the first list. The output should be

nb_zeros = c(00, 00000, 000)

I assume I have to use lapply() et rep() but they don't want to accept lists ...

If somebody have a great idea, I dont want to put some loop in that.
Thank you in advance,
Marouane

This looks like it might be a homework problem...

My advice would be to break it into pieces. Figure out how to generate the repeated number of zeros for a variable input. Then you can vectorize this operation over the list of lengths

Do something like this

library(purrr)
nb <- c(2,5,3)
nb_zeros <- nb %>% 
    map(function(x) rep(0, x))
nb_zeros
#> [[1]]
#> [1] 0 0
#> 
#> [[2]]
#> [1] 0 0 0 0 0
#> 
#> [[3]]
#> [1] 0 0 0

Created on 2019-01-04 by the reprex package (v0.2.1)

3 Likes

Thank you a lot !
That was that map function i was looking for :slight_smile:
Very grateful.

It was not a homework question and if I had someone to ask i would have. Won't post something like that here again.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.