Here is how you can use dplyr
:
library(dplyr)
test <- data.frame(A = c(1, 2, 3),
B = c(1, 1, 1),
C = c(1, 1, 1))
testColumns <- c(2, 3, 4) # Values you want to flag
Now that we have our data frame and a vector with the values we want to flag in a new column, let's use rowwise()
to tell R to look at each row of the data frame, and then a combination of mutate()
to create a new column, D, based off of various cases.
We specify the test cases and then their desired values using case_when()
.
Here's how we do it:
test <- test %>%
rowwise() %>% # Look at test on a 'by row' basis'
mutate(D = case_when(A %in% testColumns ~ 1, # use mutate to create a new column D
B %in% testColumns ~ 1,
C %in% testColumns ~ 1,
TRUE ~ 0))
This gives us the following table:
print(test)
## A tibble: 3 x 4
# A B C D
# <dbl> <dbl> <dbl> <dbl>
#1 1 1 1 0
#2 2 1 1 1
#3 3 1 1 1
Here are some helpful links for a few of the functions we used:
mutate()
rowwise()
case_when()