Reputation: 15143
I'm sorry that I cannot explain exactly. So, I'll ask with simple example.
While I'm looking at This question I use for
loop to replace yes
value to N/A
.
stim <- c("a", "k", "y", "j", "t", "Stop", "f", "l", "b", "a", "c", "Stop")
df <- data.frame(stim)
df<- df%>%
mutate(YesorNo = ifelse(stim == "Stop", "N/A", "yes"))
for (i in 1:dim(df)[1]){
if (df$YesorNo[i] == "N/A") {
if(i == 1){
} else {
df$YesorNo[i-1] = "no"
}
}
}
In for
loop above, how can I call that YesorNo[i-1]
in dplyr
?
Similarly, for a fixed number n
, how to call YesorNo[i-n]
?
Upvotes: 2
Views: 464
Reputation: 389135
You may use lag
and lead
functions in dplyr
.
library(dplyr)
df %>%
mutate(previous_value = lag(stim),
next_value = lead(stim))
# stim previous_value next_value
#1 a <NA> k
#2 k a y
#3 y k j
#4 j y t
#5 t j Stop
#6 Stop t f
#7 f Stop l
#8 l f b
#9 b l a
#10 a b c
#11 c a Stop
#12 Stop c <NA>
Note that default first and last value for lag
and lead
function is NA
respectively.
In data.table
the equivalent function is shift
-
library(data.table)
setDT(df)
df[, previous_value := shift(stim, type = 'lag')]
df[, next_value := shift(stim, type = 'lead')]
Upvotes: 2