Home > OS >  Combining elements of different lengths in matching lists in R
Combining elements of different lengths in matching lists in R

Time:01-12

I am trying to combine information from two corresponding lists, both of 4. The first list only contains 1 element for each of the 4 items, and is of the following structure:

List of 4
 $ :'data.frame':   8640 obs. of  3 variables:
  ..$ x    : num [1:8640] -108 -108 -108 -107 -107 ...
  ..$ y    : num [1:8640] 25.9 25.9 25.9 25.9 25.9 ...
  ..$ layer: num [1:8640] 0 0 0 0 0 0 0 0 0 0 ...
 $ :'data.frame':   20520 obs. of  3 variables:
  ..$ x    : num [1:20520] -116 -116 -116 -115 -115 ...
  ..$ y    : num [1:20520] 32.9 32.9 32.9 32.9 32.9 ...
  ..$ layer: num [1:20520] 0.002 0 0 0 0 ...
 $ :'data.frame':   13500 obs. of  3 variables:
  ..$ x    : num [1:13500] -112 -112 -112 -111 -111 ...
  ..$ y    : num [1:13500] 29.9 29.9 29.9 29.9 29.9 ...
  ..$ layer: num [1:13500] 0.00583 0.01166 0.01749 0.01749 0.01749 ...
 $ :'data.frame':   15300 obs. of  3 variables:
  ..$ x    : num [1:15300] -117 -117 -117 -116 -116 ...
  ..$ y    : num [1:15300] 31.9 31.9 31.9 31.9 31.9 ...
  ..$ layer: num [1:15300] 0 0 0 0 0 0 0 0 0 0 ...

I have another list that is also of 4, where I want to add the data in that list as 2 separate columns to the dataframes in their corresponding elements in the first list.

The structure of this second list is as follows:

List of 4
 $ : chr [1:2] "green" "0.00689301"
 $ : chr [1:2] "blue" "0.01291301"
 $ : chr [1:2] "red" "0.02905452"
 $ : chr [1:2] "black" "0.00879968"

Basically, I want a new list that has the following structure in each of the 4 members of the list:

List of 4
 $ :'data.frame':   8640 obs. of  3 variables:
  ..$ x    : num [1:8640] -108 -108 -108 -107 -107 ...
  ..$ y    : num [1:8640] 25.9 25.9 25.9 25.9 25.9 ...
  ..$ layer: num [1:8640] 0 0 0 0 0 0 0 0 0 0 ...
  ..$ color: chr [1:8640] "green" "green" "green"...
  ..$ value: chr [1:8640] "0.00689301" "0.00689301" ...
 $ :'data.frame':   20520 obs. of  3 variables:
  ..$ x    : num [1:20520] -116 -116 -116 -115 -115 ...
  ..$ y    : num [1:20520] 32.9 32.9 32.9 32.9 32.9 ...
  ..$ layer: num [1:20520] 0.002 0 0 0 0 ...
  ..$ color: chr [1:20520] "blue" "blue" "blue" ...
  ..$ value: chr [1:20520] "0.01291301" "0.01291301" ...

I have tried combining this information all at once using mapply() and c(), but that didn't give me the flexibility to change these new members from my second list from individual values into vectors of the same length as the corresponding new list.

CodePudding user response:

We may use Map

Map(function(x, y) transform(x, color = y[1], value = y[2]), lst1, lst2)
# or another way is
Map(function(x, y) {x[c("color", "value")] <- as.list(y); x}, lst1, lst2)

Or with map2

library(purrr)
library(dplyr)
map2(lst1, lst2, ~ .x %>%
     mutate(color = .y[1], value = .y[2]))
  • Related