I have this data frame
> df
# rn a b c d e f
# 1 1 2 NA NA NA NA
# 2 5 8 NA 4 5 6
# 3 8 5 4 2 3 2
# 4 4 2 5 5 6 2
I am trying to create a new column that's based on these conditions:
- When columns
ctofare allNA, then b - When only
cisNA, then return the smallest value in columnsb, andfi.e.min(b,f)orpmin - When no
NAsexist in the row, return the least value inb,e, andf + previous calculated value
The desired output is:
> df
# rn a b c d e f g
# 1 1 2 NA NA NA NA 2
# 2 5 8 NA 4 5 6 6 ### ? [b=8, f=6; least value = 6]
# 3 8 5 4 2 3 2 3 ### ? [b=5, e=3, 'f + previous calculated value' = 2+6=8; least value = 3]
# 4 4 2 5 5 6 2 2 ### ? [b=2, e=6, 'f + previous calculated value' = 2+3=5; least value = 2]
I have tried this but I have no idea how to access the previously calculated value (using lag(g) as a placeholder) :
df%>%
mutate(g = case_when(
is.na(c) & is.na(d) & is.na(e) & is.na(f) ~ b,
is.na(c) & !is.na(d) & !is.na(e) & !is.na(f) ~ pmin(b,f),
!is.na(c) & !is.na(d) & !is.na(e) & !is.na(f) ~ pmin(b,e, f+lag(g)),
TRUE ~ NA)
)
Maybe I am not thinking about this the right way. Any help is greatly appreciated!