Assign groups with preassigned conditions in R

3985 views r
-4

I have such a matrix(df1):

vid   col1     
103   9       
103   3       
103   7    
103   6    
104   7 
104   8  
104   9  
105   6   
105   8 
106   8  
106   9  
106   4   
106   6   

I have another matrix (df2):

vid   col1     
103   0       
104   1       
105   5    
106   3    

I want to assign groups to df1 so that group IDs are conditional on df2 based on vid.

Namely, I would like the following manipulation on df1, desired output:

   vid   col1   col2  
    103   9    0  
    103   3    0   
    103   7    0
    103   6    0
    104   7    1
    104   8    1
    104   9    1
    105   6    5  
    105   8    5
    106   8    3 
    106   9    3
    106   4    3
    106   6    3

I was trying the following:

df1<-cbind(df1,0)
for (i in 1:nrow(df1)){
  for(j in 1:nrow(df2))
{
    if(df1[i,1]==df2[j,1]){
      df1[i,3]=df2[j,2]
    }
    else{
      df1[i,3]=NA
    }

  }  
}

But this doesn't seem to work, could anyone help me with this please? Thanks!

answered question

1 Answer

12

You can use merge to merge the 2 dataframes together

merge(df1, df2, by='vid')

posted this

Have an answer?

JD

Please login first before posting an answer.