I would like to create a vector based on conditions of several other vectors. The conditions are in a decreasing order of priority. Here a simple example in which I am creating the variable 'see1' which is supposed to contain different letters (but not NA). The priority for creating it is hierarchical: l1 > l2 > l3 > l4. E.g. 'see1' can only be assigned the status of 'l4' if all other conditions are NA and it will be assigned automatically the status of 'l1' if 'l1' is not NA ('l1' overrules other columns). I have used a nested ifelse to create 'see1'.
test <- data.frame(id=c("a","b","c","d","e","f"),
l1=c(NA,NA,"A",NA,"B", NA),
l2=c(NA,NA,"N","N",NA,NA),
l3=c("V",NA,NA,NA,"V","V"),
l4=c("H","H",NA,NA,rep("H",2)), stringsAsFactors=F)
test$see1 <- ifelse(test$l1%in%c("A", "B"), test$l1,
ifelse(test$l2%in%"N", "N",
ifelse(test$l3%in%"V", "V",
ifelse(test$l4%in%"H","H", NA))))
test
id l1 l2 l3 l4 see1
1 a <NA> <NA> V H V
2 b <NA> <NA> <NA> H H
3 c A N <NA> <NA> A
4 d <NA> N <NA> <NA> N
5 e B <NA> V H B
6 f <NA> <NA> V H V
However, with many conditions/columns, this task becomes cumbersome. I have scanned similar questions about 'nested ifelse' but did not encounter this problem.