A quick question for the gurus... Given: a=c(58,73,100,40,70) b=c(40,70,73,100,58,70,70,58) How can I replace the elements of "b" with the corresponding index numbers from "a" that start at 1? All values in "a" are unique. So, I end up with: b=c(4,5,2,3,1,5,5,1) I believe I need to use one of the "apply" functions in combination with "which" but I cannot make it work. thank you, -david
replacing values in one vector with corresponding index from another vector
4 messages · Sarah Goslee, William Dunlap, David Epstein
How about a trick?
b <- as.numeric(factor(b, levels=a)) b
[1] 4 5 2 3 1 5 5 1
On Wed, Oct 19, 2011 at 5:38 PM, David Epstein <davideps at umich.edu> wrote:
A quick question for the gurus... Given: a=c(58,73,100,40,70) b=c(40,70,73,100,58,70,70,58) How can I replace the elements of "b" with the corresponding index numbers from "a" that start at 1? All values in "a" are unique. So, I end up with: b=c(4,5,2,3,1,5,5,1) I believe I need to use one of the "apply" functions in combination with "which" but I cannot make it work. thank you, -david
Sarah Goslee http://www.functionaldiversity.org
match(b, a)
[1] 4 5 2 3 1 5 5 1 Bill Dunlap Spotfire, TIBCO Software wdunlap tibco.com
-----Original Message----- From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org] On Behalf Of David Epstein Sent: Wednesday, October 19, 2011 2:39 PM To: r-help at r-project.org Subject: [R] replacing values in one vector with corresponding index from another vector A quick question for the gurus... Given: a=c(58,73,100,40,70) b=c(40,70,73,100,58,70,70,58) How can I replace the elements of "b" with the corresponding index numbers from "a" that start at 1? All values in "a" are unique. So, I end up with: b=c(4,5,2,3,1,5,5,1) I believe I need to use one of the "apply" functions in combination with "which" but I cannot make it work. thank you, -david
______________________________________________ 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.
thank you! that is straight forward.
On Wed, 2011-10-19 at 22:37 +0000, William Dunlap wrote:
match(b, a)
[1] 4 5 2 3 1 5 5 1