Hello everyone! I hope this video has helped solve your questions and issues. This video is shared because a solution has been found for the question/problem. I create videos for questions that have solutions. If you have any other issues, feel free to reach out to me on Instagram: / ky.emrah
Below, you can find the text related to the question/problem. In the video, the question will be presented first, followed by the answers. If the video moves too fast, feel free to pause and review the answers. If you need more detailed information, you can find the necessary sources and links at the bottom of this description. I hope this video has been helpful, and even if it doesn't directly solve your problem, it will guide you to the source of the solution. I'd appreciate it if you like the video and subscribe to my channel!Subtract the previous number when another row is not NA in R
This is a simplified data example.
df - data.frame(
SU = c(1, 1, NA, NA, NA, NA),
TIME = c(10, 20, 30, 40, 50, 60),
AMT = c(5, 5, NA, NA, 5, 5)
)
df - data.frame(
SU = c(1, 1, NA, NA, NA, NA),
TIME = c(10, 20, 30, 40, 50, 60),
AMT = c(5, 5, NA, NA, 5, 5)
)
I want to generate a new column TFDS, if is.na(SU) == TRUE, using TIME subtract previous AMT not NA row's TIME.
This is what I want.
SU
TIME
AMT
TFDS
1
10
5
NA
1
20
5
NA
NA
30
NA
10
NA
40
NA
20
NA
50
5
30
NA
60
5
10
SU
TIME
AMT
TFDS
1
10
5
NA
1
20
5
NA
NA
30
NA
10
NA
40
NA
20
NA
50
5
30
NA
60
5
10
SU
TIME
AMT
TFDS
SU
TIME
AMT
TFDS
SU
TIME
AMT
TFDS
1
10
5
NA
1
20
5
NA
NA
30
NA
10
NA
40
NA
20
NA
50
5
30
NA
60
5
10
1
10
5
NA
1
10
5
NA
1
20
5
NA
1
20
5
NA
NA
30
NA
10
NA
30
NA
10
NA
40
NA
20
NA
40
NA
20
NA
50
5
30
NA
50
5
30
NA
60
5
10
NA
60
5
10
I tried dplyr::lag(), but the output was not what I want.
dplyr::lag()
library(dplyr)
df - df |
mutate(
TFDS = if_else(
is.na(SU) == TRUE, TIME - lag(TIME)[!is.na(AMT)], NA
))
library(dplyr)
df - df |
mutate(
TFDS = if_else(
is.na(SU) == TRUE, TIME - lag(TIME)[!is.na(AMT)], NA
))
I believe dplyr::lag() should be used there, but how to set [!is.na(AMT)]?
dplyr::lag()
[!is.na(AMT)]
Tags: r,dplyrSource of the question:
https://stackoverflow.com/questions/7...
Question and source license information:
https://meta.stackexchange.com/help/l...
https://stackoverflow.com/
Информация по комментариям в разработке