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

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

steve zissou
1#
steve zissou Published in 2017-12-06 16:22:10Z

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?

steve zissou
2#
steve zissou Reply to 2017-12-13 17:09:36Z

Solution

To build on bouncyball's comment so you have a full answer, you can do this:

sapply(paste('val', letters[1:20], sep='_'), function(x) round(mean(get(x)), 3))

Explanation

For an object in your environment called x, get("x") will return x. See help("get"). Then we can do this for every element of paste('val', letters[1:20], sep='_') using sapply(), or if you like, a loop.

Example

val_a <- rnorm(100)
val_b <- rnorm(100)
val_c <- rnorm(100)

sapply(paste('val', letters[1:3], sep='_'), function(x) round(mean(get(x)), 3))

      val_a       val_b       val_c 
-0.09328504 -0.15632654 -0.09759111
You need to login account before you can post.

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

© 2016 Powered by mzan.com design MATCHINFO