Hello, I am looking for an elegant one-liner for the following operation: x <- rnorm(10) y <- runif(10) c(mean(x)-mean(y), mean(x)+mean(y)) I thought about apply(data.frame(x, y), 2, mean) but I don't know how to apply the +- operation on the result of apply. Thanks, *S* -- Sascha Vieweg, saschaview at gmail.com
On 04.03.2011 18:22, Sascha Vieweg wrote:> Hello, I am looking for an elegant one-liner for the following operation: > > x <- rnorm(10) > y <- runif(10) > c(mean(x)-mean(y), mean(x)+mean(y)) > > I thought about > > apply(data.frame(x, y), 2, mean) > > but I don't know how to apply the +- operation on the result of apply. > Thanks, *S* >The most elegant way probably is the way you had above for this setting, otherwise you could do, e.g.: df <- data.frame(x, y) sapply(c("-", "+"), function(f, dat) do.call(get(f), as.list(colMeans(dat))), dat = df) Uwe Ligges
On Fri, Mar 4, 2011 at 12:22 PM, Sascha Vieweg <saschaview at gmail.com> wrote:> Hello, I am looking for an elegant one-liner for the following operation: > > x <- rnorm(10) > y <- runif(10) > c(mean(x)-mean(y), mean(x)+mean(y)) > > I thought about > > apply(data.frame(x, y), 2, mean) > > but I don't know how to apply the +- operation on the result of apply.Try: mean(x) + c(-1, 1) * mean(y) -- Statistics & Software Consulting GKX Group, GKX Associates Inc. tel: 1-877-GKX-GROUP email: ggrothendieck at gmail.com
Hi Sascha, As Uwe said, I am not sure you will get more elegant. If you want it to be simple because you do it a lot and the typing is a burden, consider writing a function. Here is a little example: ########## f <- function(x, y, ...) { mx <- mean(x, ...) my <- mean(y, ...) * c(-1, 1) mx + my } f(rnorm(10), runif(10)) ########## On Fri, Mar 4, 2011 at 9:22 AM, Sascha Vieweg <saschaview at gmail.com> wrote:> Hello, I am looking for an elegant one-liner for the following operation: > > x <- rnorm(10) > y <- runif(10) > c(mean(x)-mean(y), mean(x)+mean(y)) > > I thought about > > apply(data.frame(x, y), 2, mean) > > but I don't know how to apply the +- operation on the result of apply. > Thanks, *S* > > -- > Sascha Vieweg, saschaview at gmail.com > > ______________________________________________ > R-help at r-project.org mailing list > https://stat.ethz.ch/mailman/listinfo/r-help > PLEASE do read the posting guide http://www.R-project.org/posting-guide.html > and provide commented, minimal, self-contained, reproducible code. >-- Joshua Wiley Ph.D. Student, Health Psychology University of California, Los Angeles http://www.joshuawiley.com/