Im new with R.
Currently i'm working with dplyr package for manipulation data. But i'm stuck when want to do some calculation as below:
library(dplyr)
w18 <- c(1,2,3,4,5)
w19 <- c(10,10,NA,NA,NA)
temp_df <- data.frame(w18,w19)
I expect NA will replaced with value from w19 <- ifelse(is.na(w19), lag(w19)+ lag(w18) else w19
how ever when im tried with my code as below:
w19_function <- function(temp_df) {
isna <- is.na(temp_df)
lag_w19 <- tail(temp_df[!isna],1)
loc <- length(w18[!is.na(w18),])
temp_df[isna] <- lag_w19+ temp_df[loc,'w18']
return(temp_df)
}
w19_function(temp_df)
i expect result like this one :
w18,w19
1,10
2,10
3,12
4,15
5,19
but the code giving result :
w18,w19
1,10
2,10
3,12
4,12
5,12
what thing I should to add? please help me for solving this case.
This might work as well for you:
library(tidyverse)
w18 <- c(1,2,3,4,5)
w19 <- c(10,10,NA,NA,NA)
temp_df <- data.frame(w18,w19)
temp_df
temp_df %>%
mutate(step = cumsum(if_else(is.na(w19), lag(w18), 0))) %>%
fill(w19) %>%
mutate(w19 = w19 + step) %>%
select( -step)
# w18 w19
# 1 1 10
# 2 2 10
# 3 3 12
# 4 4 15
# 5 5 19
(modified: with repeats)
temp_df %>%
mutate(grp = cumsum(if_else(!is.na(w19) & is.na(lag(w19)), 1, 0))) %>%
group_by(grp) %>%
mutate(step = cumsum(if_else(is.na(w19), lag(w18), 0))) %>%
fill(w19) %>%
mutate(w19 = w19 + step) %>%
ungroup() %>%
select( -step, -grp)
It's not easy to capture values which were changed on the fly.
Sometimes a traditional for loop can be helpful
for (i in seq_len(nrow(temp_df))) {
if(is.na(temp_df$w19[i])) {
temp_df$w19[i] <- temp_df$w18[i-1] + temp_df$w19[i-1]
}
}
temp_df
# w18 w19
#1 1 10
#2 2 10
#3 3 12
#4 4 15
#5 5 19
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With