firmo23
firmo23

Reputation: 8404

Create a new column on a dataframe based on value match with another dataframe

I have a dataframe named "INDEX" and a dataframe named "TABLE".

I would like to be able to add a new column named "ID" in the "TABLE" which will include the relative "ID" of the "INDEX" dataframe.

For example "Mark1" matches with ID=1, etc. The final result would be like:

Mark2 ID
1 Mark4  4
2 Mark4  4
3 Mark3  3
4 Mark1  1
5 Mark2  2 



    ID<-c("1","2","3","4")
    Mark=c("Mark1","Mark2","Mark3","Mark4")
    INDEX=data.frame(ID,Mark)

    Mark2=c("Mark4","Mark4","Mark3","Mark1","Mark2")
    TABLE=data.frame(Mark2)

    for(i in 1:nrow(TABLE)){
      if(INDEX[,1]==TABLE[i,1]){
        TABLE$ID<-INDEX$ID
      }
    }

Upvotes: 0

Views: 54

Answers (1)

BENY
BENY

Reputation: 323226

Using match

TABLE$ID=INDEX$ID[match(TABLE$Mark2,INDEX$Mark)]

TABLE
  Mark2 ID
1 Mark4  4
2 Mark4  4
3 Mark3  3
4 Mark1  1
5 Mark2  2

Upvotes: 1

Related Questions