[R] Conditionally swap items in a data frame

Mark Leeds markleeds at verizon.net
Thu Apr 17 17:24:44 CEST 2008

df$a<-ifelse(df1$c == 2, df$b, df$a)
df$b<-ifelse(df1$c == 2, temp, df$b)

-----Original Message-----
From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org] On
Behalf Of Michael Kubovy
Sent: Thursday, April 17, 2008 10:53 AM
To: r-help at stat.math.ethz.ch
Subject: [R] Conditionally swap items in a data frame

df1 <- data.frame(a = LETTERS[1:2], b = LETTERS[3:4], c = 1:2)

I am looking for an idiom that swaps the elements of df$a and df$b  
when (e.g.) df$c == 2, resulting in

df2 <- data.frame(a = LETTERS[c(1, 4)], b = LETTERS[c(3, 2)], c = 1:2)
Professor Michael Kubovy
University of Virginia
Department of Psychology
USPS:     P.O.Box 400400    Charlottesville, VA 22904-4400
Parcels:    Room 102        Gilmer Hall
         McCormick Road    Charlottesville, VA 22903
Office:    B011    +1-434-982-4729
Lab:        B019    +1-434-982-4751
Fax:        +1-434-982-4766
WWW:    http://www.people.virginia.edu/~mk9y/

	[[alternative HTML version deleted]]

R-help at r-project.org mailing list
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

More information about the R-help mailing list