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