Reputation: 73
Say that I have a dataframe (df) that looks like this:
stim <- c("a", "k", "y", "j", "t", "Stop", "f", "l", "b", "a", "c", "Stop")
df <- data.frame(stim)
I would like to create another column 'YesorNo' based on the value of 'stim'. My desired output is this:
stim YesorNo
a yes
k yes
y yes
j yes
t No
Stop N/A
f yes
l yes
b yes
a yes
c No
Stop N/A
... ...
I would like the value of 'YesorNo' to be N/A if stim is "stop". I can use a simple ifelse statement for that (df$YesorNo <- ifelse(df$stim=="Stop", "N/A", "yes"
) But I would also like the value that comes BEFORE "stop" (letters t and c in my example) to correspond to "no" instead of "yes". How would I define that?
Upvotes: 2
Views: 41
Reputation: 388817
You can use lead
to look for the next value and case_when
to list the conditons.
library(dplyr)
df %>%
mutate(YesorNo = case_when(stim == 'Stop' ~ NA_character_,
lead(stim) == 'Stop' ~ "No",
TRUE ~ 'Yes'))
# stim YesorNo
#1 a Yes
#2 k Yes
#3 y Yes
#4 j Yes
#5 t No
#6 Stop <NA>
#7 f Yes
#8 l Yes
#9 b Yes
#10 a Yes
#11 c No
#12 Stop <NA>
Similarly in data.table
you can use fcase
.
setDT(df)[, YesorNo := fcase(stim == 'Stop', NA_character_,
shift(stim, type = 'lead') == 'Stop', "No",
default = "Yes")]
df
Upvotes: 3
Reputation: 15123
I'm sorry that I don't know how to call next or past value in dplyr
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"
}
}
}
stim YesorNo
1 a yes
2 k yes
3 y yes
4 j yes
5 t no
6 Stop N/A
7 f yes
8 l yes
9 b yes
10 a yes
11 c no
12 Stop N/A
Upvotes: 2
Reputation: 8811
Here is a tidyverse
solution using case_when
+ operator %in%
library(tidyverse)
df %>%
mutate(
YesorNo = case_when(
stim == "Stop" ~ NA_character_,
stim %in% c("t","c") ~ "no",
#other conditions
TRUE ~ "yes"
)
)
stim YesorNo
1 a yes
2 k yes
3 y yes
4 j yes
5 t no
6 Stop <NA>
7 f yes
8 l yes
9 b yes
10 a yes
11 c no
12 Stop <NA>
Upvotes: 2