kam
kam

Reputation: 345

Assign the value in the next row if condition is met

This is the data that I have

       structure(list(id = c(1, 1, 1, 1, 1), columnA = c("2011/01/01", 
"2013/01/01", "2014/01/01", "2015/01/01", "2015/01/10"), columnB = c("NA", 
"2013/01/01", "2013/01/02", "2014/01/01", "NA")), row.names = c(NA, 
5L), class = "data.frame")

and this is what I want

  structure(list(id = c(1, 1, 1, 1, 1), A = c("2011/01/01", "2013/01/01", 
"2014/01/01", "2015/01/01", "2015/01/10"), B = c("NA", "2013/01/02", 
"NA", "2014/01/01", "NA")), row.names = c(NA, 5L), class = "data.frame")

Basically, i want if the values in columnA and columnB are equal, then bring up the value from row -1 in the same column and insert an NA in place of the value going up the column. I tried this

`library(dplyr)
data %>% 
  group_by(id) %>% 
  mutate(columnB = case_when(is.na(columnB) ~ NA_character_,
                             columnA == columnB ~ lead(columnB))) %>%
  ungroup

`

the problem is that it convert all other values in columnB to NA as well. I want where the values in A and B are not equal to remain the same and not converted to NAs.

Upvotes: 0

Views: 733

Answers (2)

NEXUSAG
NEXUSAG

Reputation: 53

aa = structure(list(
id = c(1, 1, 1, 1, 1),
columnA = c(
"2011/01/01",
"2013/01/01",
"2014/01/01",
"2015/01/01",
"2015/01/10"
),
columnB = c("NA",
          "2013/01/01", "2013/01/02", "2015/01/01", "NA")
),
row.names = c(NA,
          5L),
class = "data.frame")

bb=aa

for (i in 1:5){
 if (aa[i,2]==aa[i,3]){
bb[i,3]=bb[i+1,3] 
bb[i+1,3]="NA"
}
}

Upvotes: 0

akrun
akrun

Reputation: 887961

Based on the description, we can use lead

library(dplyr)
df1 %>% 
   group_by(id) %>% 
   mutate(columnB = case_when(is.na(columnB) ~ NA_character_,
                     columnA == columnB ~ lead(columnB))) %>%
   ungroup

Upvotes: 1

Related Questions