How to swap values in two column simultaneously with dplyr

Viewed 1674

I have the following data frame:

df <- structure(list(sqn = c("FOO", "BAR"), start = c(1, 99), end = c(531, 
1), strand = c("+", "-")), row.names = c(NA, -2L), class = c("tbl_df", 
"tbl", "data.frame"))

That looks like:

# A tibble: 2 x 4
  sqn   start   end strand
  <chr> <dbl> <dbl> <chr> 
1 FOO       1   531 +     
2 BAR      99     1 -     

What I want to do is to swap values in start and end column if strand == "-". The desired result is this:

# A tibble: 2 x 4
  sqn   start   end strand
  <chr> <dbl> <dbl> <chr> 
1 FOO       1   531 +     
2 BAR       1    99 -   

How can I achieve that?

1 Answers

An option would be

df %>% 
  mutate(start1 = ifelse(strand == "-", end, start), 
         end = ifelse(strand =="-", start, end)) %>% 
  select(sqn, start = start1, end, strand)

Or an easier option is

i1 <- df$strand == "-"
df[i1, c("start", "end")] <- df[i1, c("end", "start")]
Related