rlist

How to traverse a base R list vertically/by rows using R's characteristics


I am new to R and for a homework assignment we have to extract the first elements of each column from a list to sum these up. My current code seems to work fine but it feels like I am not using the inhert R characteristics to efficiently work with the list. (Instead it feels like I'm just applying methods to deal with lists I learned in Java) I have a list: mylist <- list(points_ex1=c(15,18,12), points_ex2=c(9,16,8), points_ex3=c(83,95,39)) and I am trying to sum up the first/second/third value of each vector respectively. For the first column this would result in 15+9+83=107

Currently I am using two nested for loops to traverse the list and then appending each element to a temporary vector, who's sum is then appended to a vector of the total points.

total_points <- NULL #object to append total scores to
for (i in 1:3){
  temp <- NULL #object to append points to
  for (j in 1:3){
    temp <- append(temp, mylist[[j]][i]) #appending the i-th element of each test score vector, before appending that sum
                                         #to the total_points vector and continuing with the next row
  }
  total_points <- append(total_points, sum(temp))
}

This works as expected, but feels like it does not use any useful R characteristics (e.g. a function like sapply()). Are there any good options to improve this code?

As this is my first question here please do tell me if I am breaking any conventions/netequitte on this site! Thank you.


Solution

  • When list items all have the same length, it's usually easier to have them as a data frame. I would do

    mylist |>
      as.data.frame() |>
      rowSums()
    # [1] 107 129  59
    

    If you don't want to rely on the list being convertible to a data frame, and instead want to extract the ith element of each item and sum them, then I would do it like this:

    i = 1
    sapply(mylist, "[", i) |>  ## extract `i`th element 
      sum()                    ## and sum
    # [1] 107
    

    Which you could then repeat for whichever values of i you want.