Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine vector and data.frame matching column values and vector values

Tags:

r

I have

vetor <- c(1,2,3)
data <- data.frame(id=c('a', 'b', 'a', 'c', 'a'))

I need a data.frame output that match each vector value to a specific id, resulting:

  id vector1
1  a       1
2  b       2
3  a       1
4  c       3
5  a       1
like image 639
Diogo Avatar asked Feb 21 '12 05:02

Diogo


1 Answers

Here are two approaches I often use for similar situations:

vetor <- c(1,2,3)
key <- data.frame(vetor=vetor, mat=c('a', 'b', 'c'))
data <- data.frame(id=c('a', 'b', 'a', 'c', 'a'))

data$vector1 <- key[match(data$id, key$mat), 'vetor']
#or with merge
merge(data, key, by.x = "id", by.y = "mat")
like image 164
Tyler Rinker Avatar answered Oct 02 '22 05:10

Tyler Rinker