Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Calculating the mean by name of a named numeric returing another named numeric as a result

I am working on a code which has a for loop. At the end of each iteration, a named numeric vector is concatenated to the one of the previous loop.

all_obj <- c()
for (i in 1:3){
  obj <- 1:3*i
  names(obj) <- c('foo', 'baz', 'bar')
  all_obj <- c(all_obj, obj)
}

At the end, all_obj looks like this:

foo baz bar foo baz bar foo baz bar 
  1   2   3   2   4   6   3   6   9 

What I would need now is to have a result which is the mean by name of this vector, and it is a named numeric itself.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Expected result

foo baz bar
  2   4   6

I know I can get the values with name foo (for example) with all_obj[names(all_obj) == "foo"]. But I am bit stuck as to how would I reach my desired result from here without having to convert the data too much (e.g. avoiding doing as.data.frame for instance). Not that there is anything wrong with this, it’s just a matter of preference and curiosity.

This was my best attempt so far.

lapply(unique(names(all_obj)), function(x) mean(all_obj[names(all_obj) == x]))
#[[1]]
#[1] 2
#
#[[2]]
#[1] 4
#
#[[3]]
#[1] 6

>Solution :

tapply is well suited for that task:

tapply(all_obj, names(all_obj), mean)

# bar baz foo 
#   6   4   2 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading