Asif
Asif

Reputation: 11

Add value from the previous row if condition is met and from the same row but different column otherwise

I am trying to add a new column to a dataframe in R based on a condition on one of the columns. If the condition is met, I want to update the cell in the new column with the value in the previous row (same column). otherwise, I want to the use the value from the column which is used in the condition. Here is an example.

Time Lptr Rptr
1 0 -1
2 -1 0
3 2 -1
4 -1 10
5 1 5

Now, I want to add a new column, called LAP based on the values in Lptr. If Lptr is equal to -1, I want to copy the LAP value from the previous row, otherwise LAP should be equal to Lptr. Here is what I want to get in the output.

Time Lptr Rptr LAP
1 0 -1 0
2 -1 0 0
3 2 -1 2
4 -1 10 2
5 -1 5 2

I use the following which gives a strange output (at least I don't understand what is happening there).

test$LAP <- ifelse(test$Lptr==-1, test$LAP[-1], test$Lptr)

Any help/pointers will be appreciated.

Upvotes: 1

Views: 2029

Answers (3)

akrun
akrun

Reputation: 887118

Using case_when

library(dplyr)
library(tidyr)
test %>%
    mutate(LAP = case_when(Lptr != -1 ~ Lptr)) %>%
     fill(LAP)
  Time Lptr Rptr LAP
1    1    0   -1   0
2    2   -1    0   0
3    3    2   -1   2
4    4   -1   10   2
5    5   -1    5   2

data

test <- structure(list(Time = 1:5, Lptr = c(0L, -1L, 2L, -1L, -1L), 
Rptr = c(-1L, 0L, -1L, 10L, 5L)), row.names = c(NA, -5L), class = "data.frame")

Upvotes: 1

Kitswas
Kitswas

Reputation: 1197

You may achieve your goal by (assuming the first Lptr is not -1):

test$LAP <- test$Lptr
for (i in 1:length(test$LAP)) {
    if(test$LAP[i] == -1)
        test$LAP[i] <- test$LAP[i-1]
}

There are other ways of doing this. I felt this method would provide a clearer understanding.

Upvotes: 1

Ronak Shah
Ronak Shah

Reputation: 388982

You may take help of replace and fill.

Change Lptr value to NA value where Lptr = -1 and fill the NA values with the previous non-NA value.

library(dplyr)
library(tidyr)

test  <- test %>%
  mutate(LAP = replace(Lptr, Lptr == -1, NA)) %>%
  fill(LAP)

test
#  Time Lptr Rptr LAP
#1    1    0   -1   0
#2    2   -1    0   0
#3    3    2   -1   2
#4    4   -1   10   2
#5    5   -1    5   2

data

test <- structure(list(Time = 1:5, Lptr = c(0L, -1L, 2L, -1L, -1L), 
Rptr = c(-1L, 0L, -1L, 10L, 5L)), row.names = c(NA, -5L), class = "data.frame")

Upvotes: 1

Related Questions