We could make use of the 'Unit_List' to create a factor
with levels
based on that list
, then select the first
level
after dropping the unused levels
, grouped by 'ID'
library(dplyr)
Unit_List = c("EM", "NAM", "AO")
x %>%
group_by(ID) %>%
mutate(Unit_New1 = levels(droplevels(factor(Unit, levels = Unit_List)))[1])
# A tibble: 10 x 5
# Groups: ID [5]
# CD ID Unit Unit_New Unit_New1
# <int> <int> <chr> <chr> <chr>
# 1 1 222 EM EM EM
# 2 2 222 EM EM EM
# 3 3 555 NAM NAM NAM
# 4 4 555 NAM NAM NAM
# 5 5 555 GT NAM NAM
# 6 6 777 GT EM EM
# 7 7 777 EM EM EM
# 8 8 999 EM EM EM
# 9 9 999 AO EM EM
#10 10 111 AO AO AO
data
x <- structure(list(CD = 1:10, ID = c(222L, 222L, 555L, 555L, 555L,
777L, 777L, 999L, 999L, 111L), Unit = c("EM", "EM", "NAM", "NAM",
"GT", "GT", "EM", "EM", "AO", "AO"), Unit_New = c("EM", "EM",
"NAM", "NAM", "NAM", "EM", "EM", "EM", "EM", "AO")),
class = "data.frame", row.names = c("1",
"2", "3", "4", "5", "6", "7", "8", "9", "10"))