3

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?

littleworth
  • 4,781
  • 6
  • 42
  • 76

1 Answers1

7

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")]
akrun
  • 874,273
  • 37
  • 540
  • 662
  • Hi @akrun, If you had many columns, is there an option for ```select``` to get all other columns automatically and then specify just ```start = start1```? – Russ Thomas Apr 19 '20 at 21:57
  • 1
    @RussThomas Yes, you can do `select(start = start1, everything())` – akrun Apr 19 '20 at 21:58
  • 3
    @RussThomas because you are renaming the column, more correct is `select(start = start1, everything(), -start1)` – akrun Apr 19 '20 at 22:00