Re: [R] Mapping from one vector to another

2014-07-17 Thread Gang Chen
Jeff, Even though the solutions from the previous responders are good enough for my current situation, the principle you just raised will be definitely beneficial to your future work. Thanks a lot for sharing the insights! Gang On Thu, Jul 17, 2014 at 12:06 PM, Jeff Newmiller wrote: > You ask a

Re: [R] Mapping from one vector to another

2014-07-17 Thread Jeff Newmiller
You ask about generic methods for introducing alternate values for factors, and some of the other responses address this quite efficiently. However, a factor has meaning only within one vector at a time, since another vector may have additional values or missing values relative to the first vect

Re: [R] Mapping from one vector to another

2014-07-17 Thread Gang Chen
Thanks a lot for the quick and elegant solutions, Sarah, Bill and Petr! I really appreciate it, including the suggestion of setting a random seed. Have a nice day! Gang On Thu, Jul 17, 2014 at 11:15 AM, Sarah Goslee wrote: > What about: > > d$var <- c(8, 11, 3, 2)[d$fac] > > Side note: it's much

Re: [R] Mapping from one vector to another

2014-07-17 Thread PIKAL Petr
[mailto:r-help-bounces@r- > project.org] On Behalf Of Gang Chen > Sent: Thursday, July 17, 2014 5:00 PM > To: r-help > Subject: [R] Mapping from one vector to another > > Suppose I have the following dataframe: > > L4 <- LETTERS[1:4] > fac <- sample(L4, 10, replace = T

Re: [R] Mapping from one vector to another

2014-07-17 Thread Sarah Goslee
What about: d$var <- c(8, 11, 3, 2)[d$fac] Side note: it's much appreciated that you included data and a clear problem statement. If you use set.seed(123) before your call to sample(), everyone who tries it will get the same fac that you do. Otherwise we all get something different. Or just gener

Re: [R] Mapping from one vector to another

2014-07-17 Thread William Dunlap
One way is to use a vector with names to do the mapping: > mapVector <- c(A=8, B=11, C=3, D=2) > mapVector[as.character(d$fac)] B B D A C D C B B B 11 11 2 8 3 2 3 11 11 11 > # you may want to wrap this with unname() > d$mappedFac <- mapVector[as.character(d$fac)] > d x y fac map

[R] Mapping from one vector to another

2014-07-17 Thread Gang Chen
Suppose I have the following dataframe: L4 <- LETTERS[1:4] fac <- sample(L4, 10, replace = TRUE) (d <- data.frame(x = 1, y = 1:10, fac = fac)) x y fac 1 1 1 B 2 1 2 B 3 1 3 D 4 1 4 A 5 1 5 C 6 1 6 D 7 1 7 C 8 1 8 B 9 1 9 B 10 1 10 B I'd like to add an