R :: Returns the first occurrence of a row variable as a new column

advertisements

I have been fumbling badly with the apply function. I have a list of single character values and would like to return the first mention of a vowel.

a<- c("A","B","C","E")
b<- c("O","T","D","J")
c<- c("A","R","B","K")
d<- c("F","L","O","U")
e<- c("N","D","S","Z")

df <- data.frame(a,b,c,d,e)

I'd like to create a new column that returns the first instance of a vowel for that row.

vow <- c("A","E","I","O","U")

The result would be (A,NA?,O,E), how would you handle if no value is found?


This works and will give you a warning if no letters is found. You can elaborate the function to catch this as well.

apply(df, 1, function(x, vow) x[min(which(x %in% vow))], vow = vow)
[1] "A" NA  "O" "E"