Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Appending List Elements in R

I have two large, ordered lists of integers. I would like the integer length at [i]position of hello to be equal to the length at [i] position of bye.

Here is a simplified reproducible example to simulate my dataset :

c1<- c(0,1,0,1,1,1,0,0) |> as.integer()
c2<- c(0,1,0) |> as.integer()
c3<- c(1,1,1,0,0,0,0,0,0) |> as.integer()
c4<- c(0,1,0,1,0,0,0,1,0,1) |> as.integer()
c5<- c(0,1,0,1,0,0,0,0) |> as.integer()
c6 <-  c(1,1,1,0,0) |> as.integer()

hello<- list(c1, c2, c3)
bye<- list(c4,c5,c6)

Lists output:

hello
[[1]]
[1] 0 1 0 1 1 1 0 0

[[2]]
[1] 0 1 0

[[3]]
[1] 1 1 1 0

bye
[[1]]
 [1] 0 1 0 1 0 0 0 1 0 1

[[2]]
[1] 0 1 0 1 0 0 0 0

[[3]]
[1] 1 1 1 0 0

I would like the values of the expanded relevant list element to be appended with values of 0. The desired output of an individual list element would look like this:

hello[[2]]
[1] 0 1 0 0 0 0 0 0

bye[[2]]
[1] 0 1 0 1 0 0 0 0

So far, I have tried a for loop with an append statement which I just couldn't get to work.

I assume that lapply or purrr::map would provide a neater solution but I am still trying to get my head around functional programming in R. Any help would be greatly appreciated.

like image 334
AR459 Avatar asked Sep 07 '25 17:09

AR459


1 Answers

You could try:

Map(\(x, y) c(x, integer(y))[1L:y], hello, pmax(lengths(hello), lengths(bye)))

Or a slight variation:

Map(\(x, y, z) c(x, integer(max(0L, z-y))), hello, lengths(hello), lengths(bye))

[[1]]
 [1] 0 1 0 1 1 1 0 0 0 0

[[2]]
[1] 0 1 0 0 0 0 0 0

[[3]]
[1] 1 1 1 0 0 0 0 0 0
like image 112
Ritchie Sacramento Avatar answered Sep 10 '25 07:09

Ritchie Sacramento