0

I have two lists that contain 500 data frames. Here is an example of two lists containing 2 data frames each.

 l1
    [[1]]
      X1 X2 X3
    1  1  0  0
    2  5  1  8

    [[2]]
      X1 X2 X3
    1  0  1  1
    2  3  0  4

and

l2
   [[1]]
      X1 X2 X3
    1  1  1  0
    2  0  1  1

    [[2]]
      X1 X2 X3
    1  0  1  0
    2  0  1  1

I need to sum the last value in a column of a dataframe, to the first value of the same column in a dataframe in a different list. For instance:

l1[[1]]$x1[2] to l2[[1]]$x1[1] ; and l1[[1]]$x3[2] to l2[[1]]$x3[1] 

In my example, the intended result should be recorded in the dataframes contained in l2, and should look like this:

> l2
[[1]]
  X1 X2 X3
1  6  2  8
2  0  1  1

[[2]]
  X1 X2 X3
1  3  1  4
2  0  1  1

I intend to do this with lists that contain 500 dataframes. I would have preference for Dplyr.

JPV
  • 323
  • 2
  • 10
  • You can use the [`reprex`](https://reprex.tidyverse.org/articles/articles/magic-reprex.html) and [`datapasta`](https://cran.r-project.org/web/packages/datapasta/vignettes/how-to-datapasta.html) packages to quickly create a reproducible example so others can help. See also [Help me Help you](https://speakerdeck.com/jennybc/reprex-help-me-help-you?slide=5) & [How to make a great R reproducible example?](https://stackoverflow.com/q/5963269) – Tung Oct 12 '18 at 05:00

1 Answers1

0

Try Map/mapply:

# data
l1 <- list("X1 X2 X3
1  1  0  0
          2  5  1  8",
          "X1 X2 X3
1  0  1  1
          2  3  0  4")

l1 <- lapply(l1, function(x) read.table(text = x, header = TRUE))

l2 <- list("X1 X2 X3
1  1  1  0
           2  0  1  1",
           "X1 X2 X3
1  0  1  0
           2  0  1  1")
l2 <- lapply(l2, function(x) read.table(text =x, header = T))

# Map
Map(function(a, b) rbind(a[2, ] + b[1,  ], b[2, ]), l1, l2)

# [[1]]
# X1 X2 X3
# 2   6  2  8
# 21  0  1  1
# 
# [[2]]
# X1 X2 X3
# 2   3  1  4
# 21  0  1  1

OR:

library(tidyverse)
map2(l1, l2, ~bind_rows(.x %>%
                          slice(2) %>%
                          bind_rows(.y %>%
                                      slice(1)) %>%
                          summarise_all(funs(sum)), 
                        .y %>%
                          slice(2)))
r.user.05apr
  • 5,356
  • 3
  • 22
  • 39
  • If I try to reproduce it straight away `Realizations<-lapply(Realizations,function(x) read.table(text= x, header = TRUE))` it gives an error _invalid 'text argument'_ – JPV Oct 12 '18 at 06:49
  • No quite sure about the error. Try to add `stringsAsFactors=F` (https://stat.ethz.ch/pipermail/r-help/2011-July/284044.html ). – r.user.05apr Oct 12 '18 at 07:12
  • almost, but I need to sum elements in columns 1 and 3 in my example. In my real dataset, need to sum elements in column 25, 45, and 79. Thanks a lot for your answers though. I appreciate that you're trying to help me. – JPV Oct 12 '18 at 08:12