R matching more than 2 conditions and return the response value

前端 未结 4 1870
名媛妹妹
名媛妹妹 2021-01-18 20:25

Hi I have two data set where the first one is a set of index:

ind1<-rep(c(\"E\",\"W\"), times=20)
ind2<-sample(100:150, 40)
y<-c(1:40)
index<-dat         


        
4条回答
  •  执笔经年
    2021-01-18 20:31

    This question is related to match two data.frames based on multiple columns.

    You can use interaction or paste as already suggested by Dinre, to match on multiple columns.

    #Write the row number of index in x3 which matches
    data$x3 <- match(interaction(data[c("x1", "x2")]), interaction(index[c("ind1","ind2")]))
    
    #In case you want to return 0 instead of NA for nomatch
    data$x3 <- match(interaction(data[c("x1", "x2")]), interaction(index[c("ind1","ind2")]), nomatch=0)
    
    #Instead of >interaction< you could also use paste as already suggested by Dinre
    data$x3 <- match(paste(data$x1, data$x2), paste(index$ind1, index$ind2))
    
    

提交回复
热议问题