David Moore
David Moore

Reputation: 1020

Adding a vector to components of a list

I have the following list:

A <- c(11)
B <- c(7, 13)
C <- c(1, 10, 11, 12)
my_list <- list(A, B, C)
> my_list
[[1]]
[1] 11

[[2]]
[1]  7 13

[[3]]
[1]  1 10 11 12

I would like to add -2, -1, 0, 1, and 2 to each number in this list, and retain all of the unique values within each list element, to obtain the following resulting list:

> my_new_list
[[1]]
[1] 9 10 11 12 13

[[2]]
[1]  5 6 7 8 9 11 12 13 14 15

[[3]]
[1]  -1 0 1 2 3 8 9 10 11 12 13 14

I tried the following code, but I did not get the result I was hoping for:

my_new_list <- lapply(res, `+`, -2:2)
> my_new_list
$`1`
[1]  9 10 11 12 13

$`2`
[1]  5 12  7 14  9

$`3`
[1] -1  9 11 13  3

Why is this happening, and how can I obtain the result I'd like? Thanks!

Upvotes: 2

Views: 42

Answers (2)

gaut
gaut

Reputation: 5958

How about this:

my_new_list <- lapply(my_list, function(x) unique(union(x,sapply(x, function(y) y +c(-2:2))    )))
my_new_list <-  lapply(my_new_list, sort)
my_new_list

[[1]]
[1]  9 10 11 12 13

[[2]]
 [1]  5  6  7  8  9 11 12 13 14 15

[[3]]
 [1] -1  0  1  2  3  8  9 10 11 12 13 14

Upvotes: 2

akrun
akrun

Reputation: 887951

Assuming that we need the unique values

lapply(my_list, function(x) sort(unique(unlist(lapply(x, `+`, -2:2)))))

Or with outer

lapply(my_list, function(x) sort(unique(c(outer(x, -2:2, `+`)))))

Or with rep and recyling

lapply(my_list, function(x) sort(unique(rep(-2:2, each = length(x)) + x)))
#[[1]]
# [1]  9 10 11 12 13

#[[2]]
# [1]  5  6  7  8  9 11 12 13 14 15

#[[3]]
# [1] -1  0  1  2  3  8  9 10 11 12 13 14

Upvotes: 3

Related Questions