如何使用dplyr同时交换两列中的值

时间:2019-06-06 06:04:30

标签: r dplyr tidyverse

我有以下数据框:

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"))

看起来像:

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

我想做的是交换startend列中的值 strand == "-"。理想的结果是这样的:

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

我该如何实现?

1 个答案:

答案 0 :(得分:5)

一个选项是

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

或更简单的选择是

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