Dan KS
Dan KS

Reputation: 143

R:: Return the First Occurence of a Variable in a Row as New Column

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?

Upvotes: 1

Views: 105

Answers (2)

Neal Fultz
Neal Fultz

Reputation: 9687

> m <- apply(df, 1, match, table=vow)
> 
> i <- apply(m, 2, function(x) na.omit(x)[1])
> 
> vow[i]
[1] "A" NA  "O" "E"

In three steps:

1) Apply match to each row, get a table of indexes (transposed!)

2) Get the first non-NA from each column

3) look up index in vow

Upvotes: 0

Roman Luštrik
Roman Luštrik

Reputation: 70633

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"

Upvotes: 1

Related Questions