Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Subtracting 1 in a column after a specific row in R

I have a dataframe that looks like this:

example <- data.frame(
  `Event Full` = c('SocReframeNeg',
                   'SocReframeNeg',
                   'test',
                   'SocReframeNeg',
                   'SocReframeNeg',
                   'SocImmerseNeg',
                   'SocImmerseNeg'),
  Num = c(1,2,3,4,5,6,7)
)

I want to subtract 1 from Num for all rows after ‘test’, and then remove the row with ‘test’ from the dataframe.

This is the output:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

solution <- data.frame(
  `Event Full` = c('SocReframeNeg',
                   'SocReframeNeg',
                   'SocReframeNeg',
                   'SocReframeNeg',
                   'SocImmerseNeg',
                   'SocImmerseNeg'),
  Num = c(1,2,3,4,5,6)
)

Does anyone know an efficient way to solve this?

Thank you!

>Solution :

You can do it like this:

i_test <- which(example[["Event.Full"]] == "test")
example$Num[i_test:nrow(example)] <- example$Num[i_test:nrow(example)] - 1
example <- example[-i_test, ]
example
##      Event.Full Num
## 1 SocReframeNeg   1
## 2 SocReframeNeg   2
## 4 SocReframeNeg   3
## 5 SocReframeNeg   4
## 6 SocImmerseNeg   5
## 7 SocImmerseNeg   6

Note that data.frame() has replaced the space in the column name "Event Full" by a dot. If you don’t want this, you have to call data.frame() with check.names = FALSE like this:

example <- data.frame(
  `Event Full` = c('SocReframeNeg',
                   'SocReframeNeg',
                   'test',
                   'SocReframeNeg',
                   'SocReframeNeg',
                   'SocImmerseNeg',
                   'SocImmerseNeg'),
  Num = c(1,2,3,4,5,6,7),
  check.names = FALSE
)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading