Home > front end >  Calculating the mean by name of a named numeric returing another named numeric as a result
Calculating the mean by name of a named numeric returing another named numeric as a result

Time:02-08

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.

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

CodePudding user response:

tapply is well suited for that task:

tapply(all_obj, names(all_obj), mean)

# bar baz foo 
#   6   4   2 

CodePudding user response:

An other way in base R is to split all_obj according to names, and calculate mean for each group using sapply.

sapply(split(all_obj, names(all_obj)), mean)
bar baz foo 
  6   4   2 

CodePudding user response:

Sorry, this was very easy....

I am posting the solution here so that it hopefully help anyone with my same requirement.

sapply(unique(names(all_obj)), function(x) mean(all_obj[names(all_obj) == x]))

Result

foo baz bar 
  2   4   6 
  •  Tags:  
  • Related