[R] Seeking help re: ? single apply command or an alternative

From: Min-Han Tan <minhan.science_at_gmail.com>
Date: Thu, 21 Apr 2011 23:34:58 -0400


Dear R-help list,

Sorry to trouble everyone. This seems like it could be achieved with a single command (? variant of apply), but I am not quite seeing it.

I am trying to multiply one vector (a1 below) by corresponding values in a3 (as determined by matching element in a vector a2). The example below might be clearer.

a1 <- c(4,3,4,6,8,9,2,3,4,6,7,4)
a2 <- c("A","A","A","A","B","B","C","C","C","D","D","D")
a3 <- c(2,4,1,0.5)

names(a3) <- c("A","B","C","D")

I would like the vector (8,6,8,12,32,36,2,3,4,3,3.5,2) as my final output result i.e. multiply each element of a1 by the matching a3 as determined by the corresponding element of a2 - that is, for the first 4 elements of a1, multiply by the value 2 found in a3 ("A"), the next 2 by 4 ("B"), the next 3 by 1.0 ("C"), and the last 3 by 0.5 ("D")

I am trying to avoid the use of loops, because the actual dataset is much larger.

Thanks very much!

Min-Han

        [[alternative HTML version deleted]]



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. Received on Fri 22 Apr 2011 - 03:37:29 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Fri 22 Apr 2011 - 04:00:32 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive