[R] Seeking help re: ? single apply command or an alternative
Niels Richard Hansen
Niels.R.Hansen+lists at math.ku.dk
Fri Apr 22 05:49:54 CEST 2011
a1 * a3[a2]
- Niels
> 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.
On 21/04/11 23.34, Min-Han Tan wrote:
--
Niels Richard Hansen Web: www.math.ku.dk/~richard
Associate Professor Email: Niels.R.Hansen at math.ku.dk
Department of Mathematical Sciences nielsrichardhansen at gmail.com
University of Copenhagen Skype: nielsrichardhansen.dk
Universitetsparken 5 Phone: +1 510 502 8161
2100 Copenhagen Ø
Denmark
More information about the R-help
mailing list