-1

Consider this code

lapply(lst,rowSums)

lst is a list of five data frames. Each data frame has, for example, four columns and ten rows. I want to add the values of the columns in each row, however, I do not want to include the value of column one in the sum.

I can use a for loop and the code below:

lst_sum = list()
for (ii in c(1,5))
{
 dummy <- lst[[ii]]
 dummy <- rowSums(dummy[,seq(2,4,by = 1)])
 lst_sum[[ii]] = dummy 
 }

I would like to use lapply or a similar function because I think the for loops looks ugly and inefficient.

MOON
  • 2,516
  • 4
  • 31
  • 49
  • 1
    Try something like `lapply(lst, function(x) rowSums(x[, -1]))`? More fully reproducible example for what you need is: `df <- data.frame(x = 1:10, y = 1:10, z = 1:10); l = list(df, df, df, df, df); lapply(l, function(x) rowSums(x[, -1]));` – Gopala May 14 '17 at 14:37
  • Did you meant `Reduce("+", lst)` It is not clear without a reproducible example Or try `lapply(lapply(lst, "[", -1), rowSums)` – akrun May 14 '17 at 14:37

1 Answers1

0

With the help of comments I got this solution:

 lapply(lst,function(x) rowSums(x[,seq(2,4,by = 1)]))
MOON
  • 2,516
  • 4
  • 31
  • 49