I have two data frames, myDF
and index
, and I efficiently match between the two as shown below where I create a new column in data frame myDF
called alloc_1
which is based on row matches it finds in data frame Index
(where row number in data frame index
matches eleCnt
in data frame myDF
):
Preferably using my existing mutate()
as a starting point where I especially like index$index[eleCnt]
for identifying the index row number, how can I further restrict matching from data frame index
to only those rows where cumGrp
= 1? Resulting in the below pretend output:
eleCnt concat_1 alloc_1 explanation
1 1 1.0 10.0
2 2 2.0 NA since index row 2 cumGrp <> 1, don't match it
3 1 1.0 10.0
4 2 2.1 NA since index row 2 cumGrp <> 1, don't match it
5 3 2.2 NA
Below is code for myDF
, index
, and the dplyr mutate()
:
myDF <- data.frame(
eleCnt = c(1,2,1,2,3),
concat_1 = c(1,2,1,2.1,2.2)
)
index <- data.frame(
index = c(10,2.1),
cumGrp = c(1,2)
)
library(dplyr)
myDF %>% mutate(alloc_1 = index$index[eleCnt])