Home > Software engineering >  Sum only the numeric parts in a list
Sum only the numeric parts in a list

Time:10-08

I want to create a function that will take a list (we can call it x) and then sum together all of the numeric elements from the list. This should be pretty straightforward I believe, but as I am fairly new to R programming I have not been successful. We already have a matrix function created

a_matrix <- function(){
   matrix(1:9, nrow = 3)
}

And let's say our list is as following:

my_list <- function(){
   list(topic = "brand", c(1.04, 45, 87, 12), a_matrix)
}

An I want to sum the numeric values (so not topic = "brand"). i was thinking of using if and else and use is.numeric in a function like the one here:

sum_num <- function(x){
   
}

And then when I run my sum_num-function as below, I want to get one value that is the sum of every numeric value.

the_list <- my_list()
sum_num(x = the_list)
sum_num(x = the_list [2])

I was thinking I could also utilise sum(x, na.rm = FALSE, …), but I can't seem to get it to work.

CodePudding user response:

library(tidyverse)

sum_list <- function(x) {
  x %>%
    flatten() %>%
    keep(is.numeric) %>%
    reduce(sum) 
}

sum_list(
  list(topic = "brand", c(1.04, 45, 87, 12), matrix(1:9, nrow = 3))
)
#> [1] 190.04

Created on 2021-10-07 by the reprex package (v2.0.1)

CodePudding user response:

Does this do the trick??

test= function(i){
  if(is.numeric(i)){
    return(sum(i))
  }
}
unlist(lapply(the_list, test))

output:

145.04 

If you want to take into account the matrix:

sum(unlist(lapply(the_list, test))) 

output:

190.04

If you want to have it all in one call:

test= function(i){
  if(is.numeric(i)){
    return(sum(i))
  }
}

 sum_num= function(j)(sum(unlist(lapply(j, test))))


sum_num(the_list)
  •  Tags:  
  • r
  • Related