Home R: created a names vector containing the means of multiple numeric vectors
Reply: 0

R: created a names vector containing the means of multiple numeric vectors

user1347 Published in April 27, 2018, 6:42 am

I have over 20 numeric vectors which consist of a series of values. each vector is distinguished by a letter, e.g. val_a, val_b, val_c etc...

I would like to put the means from each of these vectors into a single named vector. I could of course do this in a laborious manner like so:

obs <- c("val_a" = round(mean(val_a),3),
         "val_b" = round(mean(val_b),3),
         "val_c" = round(mean(val_c),3))

But with 20 vectors this then becomes tedious to write out, and not to mention an inelegant solution. How can I create the named vector in a more succinct way? I have made an attempt using a for loop, as so:

obs <- c(for (j in 1:20) {
  assign(paste("val",letters[j], sep = "_"), 
  mean(as.name(paste('val',letters[j], sep = '_'))),)

In the right hand argument passed to assign, "as.name" is used in order to remove the quotation marks from output of "paste". So the second argument passed to assign returns a character which has the exact same name as the numeric vector that I want get the mean of, e.g. val_a. But I get the error messsage:

Warning messages: 1: In mean.default(as.name(paste("val", letters[j], sep = "_"))) : argument is not numeric or logical: returning NA

Does anyone know how to accomplish this?

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.37233 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO