Re: [R] Efficient swapping

2017-07-07 Thread Anthoni, Peter (IMK)
how about gdata functions? set.seed(1) (tmp <- data.frame(x = 1:10, R1 = sample(LETTERS[1:5], 10, replace = TRUE), R2 = sample(LETTERS[2:6], 10, replace = TRUE))) tmp.orig=tmp library(gdata) bigMap=mapLevels(x=list(factor(tmp[,"R1"]),factor(tmp[,"R2"])),combine = T,codes=FALSE) mapLevels(tmp[,"

Re: [R] Efficient swapping

2017-07-06 Thread Jeff Newmiller
No, that would remap B to A. Convert to character before doing this, then back to factors. -- Sent from my phone. Please excuse my brevity. On July 6, 2017 4:43:00 PM PDT, Ista Zahn wrote: >Untested, but I expect that setting the levels to be the same across >the >two factors > >levels(tmp$R1)

Re: [R] Efficient swapping

2017-07-06 Thread Ista Zahn
Untested, but I expect that setting the levels to be the same across the two factors levels(tmp$R1) <- levels(tmp$R2) <- LETTERS[1:6] and proceeding as before should be fine. Best, Ista On Jul 6, 2017 6:54 PM, "Gang Chen" wrote: Thanks a lot, Ista! I really appreciate it. How about a slightl

Re: [R] Efficient swapping

2017-07-06 Thread Gang Chen
Thanks a lot, Ista! I really appreciate it. How about a slightly different case as the following: set.seed(1) (tmp <- data.frame(x = 1:10, R1 = sample(LETTERS[1:5], 10, replace = TRUE), R2 = sample(LETTERS[2:6], 10, replace = TRUE))) x R1 R2 1 C B 2 B B 3 C E 4 E C 5

Re: [R] Efficient swapping

2017-07-06 Thread Ista Zahn
How about foo <- with(list(r1 = tmp$R1, r2 = tmp$R2, swapme = (as.numeric(tmp$R1) - as.numeric(tmp$R2)) %% 2 != 0), { tmp[swapme, "R1"] <- r2[swapme] tmp[swapme, "R2"] <- r1[swapme] tmp }) Best, Ista On Thu, Jul 6, 2017 at 4:06 PM, Gang Chen wrote:

[R] Efficient swapping

2017-07-06 Thread Gang Chen
Suppose that we have the following dataframe: set.seed(1) (tmp <- data.frame(x = 1:10, R1 = sample(LETTERS[1:5], 10, replace = TRUE), R2 = sample(LETTERS[1:5], 10, replace = TRUE))) x R1 R2 1 1 B B 2 2 B A 3 3 C D 4 4 E B 5 5 B D 6 6 E C 7 7 E D 8 8 D E 9 9