aminards
aminards

Reputation: 421

How can I increment a value in a data frame without creating a new column?

I have a data frame like this:

chr    start    stop
chr1    1    500
chr1    1000    1500
chr1    1500    1500

I need to find the rows where start and stop are the same and increment stop by 1. So pseudo code might look like this

if start = stop, stop+1

I would like to use dplyr if possible. I have found examples that could do this by adding a new column. I need to edit the value in-line.

My expected outcome for the example data would be:

chr    start    stop
chr1    1    500
chr1    1000    1500
chr1    1500    1501

Where the value for row 3 column stop increased by 1.

Upvotes: 1

Views: 292

Answers (2)

Omar
Omar

Reputation: 57

chr <- rep("chr1",3)
start <- c(1,1000, 1500)
stop <-c(500,1500,1500)


df <- data.frame(chr,start,stop)

df %>%
  mutate(stop = ifelse(start == stop, stop+1,stop))

Upvotes: 2

Anoushiravan R
Anoushiravan R

Reputation: 21938

I think you can use this simple solution:

library(dplyr)

df %>%
  mutate(stop = ifelse(start == stop, stop + 1, stop))

   chr start stop
1 chr1     1  500
2 chr1  1000 1500
3 chr1  1500 1501

Upvotes: 2

Related Questions