0

I want to sum multiple columns of matrices in a list and only show the sum without showing the (calculation) input columns (similar to my former question on data frames). Thanks for the former answers, however I struggled to implement the ideas on matrices. Here an example:

ls <- list(matrix(c(1, 5, 3, 2), ncol=4), matrix(c(NA, 2, 7, 9), ncol=4))
countries <- c("a", "b", "c", "d")
ls <- lapply(ls, "colnames<-", countries)

my expected result is:

[[1]]
     c new
[1,] 3   8

[[2]]
     c new
[1,] 7  11

Any ideas how to do this column summation? Thanks

Community
  • 1
  • 1
N.Varela
  • 910
  • 1
  • 11
  • 25
  • Can you explain please your desired output? Why are you keeping `c` column? How is this different from the original question? What is your desired output for 200 columns? – David Arenburg Sep 25 '16 at 19:24
  • c was only an example.. I have country columns which I want to add to regions. The only difference is that I asked before for data frames and now for matrices. – N.Varela Sep 25 '16 at 19:57

1 Answers1

1

Try below:

calc <- c("a", "b", "d")
keep <- "c"

lapply(ls, function(i){
  cbind(i[, keep, drop = FALSE],
        new = rowSums(i[, calc, drop = FALSE], na.rm = TRUE))
  })
zx8754
  • 52,746
  • 12
  • 114
  • 209
  • works fine for the example. However, cbind(i[, "c"... (especially "c") is not suitable for my data as I have > 200 columns. Therefore I need a general solution without naming colums. – N.Varela Sep 25 '16 at 19:16
  • @N.Varela then you can keep "c" as variable as well outside lapply? – zx8754 Sep 25 '16 at 19:17
  • @N.Varela I think your example is not representative of what you are trying to achieve, please make your data more "real" and show the "real " calculation logic. – zx8754 Sep 25 '16 at 19:19
  • Thanks.. I tried: `keep <- COUNTRIES [! COUNTRIES %in% calc]` (COUNTRIES are all my colnames) which works fine – N.Varela Sep 25 '16 at 19:53