Reputation: 899
I am trying to create another column in the data frame based on the condition in one column and values in another column. My data frame looks like:
ID<-c(1,2,3,4,5,6,7,8,9,10)
Stock_ret <- c(-0.4, 0.5, 0.6,NA, NA, -0.8, -00.1, NA,-0.15, .28)
Covid.cases <- c(20, 200, 34, 10, 43, 15,11,3,4,55)
df1<-data.frame(ID, Stock_ret, Covid.cases)
The new column should take the values from covid.case column and add the current and last two values in case two consecutive NA are found in Stock_ret column. The new column should look like:
c.covid.case.trading<-c(20,200,34,10,43,68,11,3,7,55)
df2<-data.frame(ID, Stock_ret, Covid.cases, c.covid.case.trading)
I have searched the forum for the similar answers but my hardluck, the current solutions are not fitting in this scenario. Kindly help.
Upvotes: 0
Views: 42
Reputation: 51894
With lag
+ ifelse
:
df1 %>%
mutate(new_col = ifelse(is.na(lag(Stock_ret, default = 0)) & is.na(lag(Stock_ret, n = 2)),
Covid.cases + lag(Covid.cases) + lag(Covid.cases, n = 2), Covid.cases))
# ID Stock_ret Covid.cases new_col
# 1 1 -0.40 20 20
# 2 2 0.50 200 200
# 3 3 0.60 34 34
# 4 4 NA 10 10
# 5 5 NA 43 43
# 6 6 -0.80 15 68
# 7 7 -0.10 11 11
# 8 8 NA 3 3
# 9 9 -0.15 4 4
# 10 10 0.28 55 55
Upvotes: 3