I am wanting to look through the the unit column and the POSN column to see it the Unit has a MSTC and mark a 1 in a new column for all the Units that has an MSTC.
CodePudding user response:
A simple solution in base R would go something like the following code snippet. This solution only does exact matching. If you're looking for partial matches or pattern matching try pmatch
or grep
.
dfrm <- data.frame(Unit = c("Arista", "Clearwater", "Kodiak"),
POSN = c("MST2", "MSTC", "MST3"))
dfrm$mark <- 0
dfrm$mark[dfrm$POSN == "MSTC"] <- 1
A tidyverse solution would be
library(tidyverse) # actually only dplyr required
dfrm %>% mutate(mark = if_else(POSN == "MSTC", 1, 0))
EDIT: Thank for clarifying the question. When you want to mark all Units that (in some row) may have contained "MSTC" in POSN you could do sth like the following:
to_mark <- dfrm$Unit[dfrm$POSN == "MSTC"]
dfrm$mark <- 0
dfrm$mark[dfrm$Unit %in% to_mark] <- 1
Hope this helps