Home > Software engineering >  How to extract elements from vector using another vector with non unique values?
How to extract elements from vector using another vector with non unique values?

Time:09-20

I have two vectors:

duplicated_q <- c(q142 = "q42", q143 = "q43", q144 = "q44", q145 = "q45", q146 = "q46", 
q192 = "q42", q193 = "q43", q194 = "q44", q195 = "q45", q196 = "q46", 
q197 = "q47", q198 = "q48", q199 = "q49", q200 = "q50", q201 = "q51")

modified_q <- c(q42 = "q22", q42 = "q32", q43 = "q23", q43 = "q33", q44 = "q24", 
q44 = "q34", q45 = "q25", q45 = "q35", q46 = "q26", q46 = "q36", 
q47 = "q27", q48 = "q28", q49 = "q29", q50 = "q30", q51 = "q31"
)

> duplicated_q
q142  q143  q144  q145  q146  q192  q193  q194  q195  q196  q197  q198  q199  q200  q201 
"q42" "q43" "q44" "q45" "q46" "q42" "q43" "q44" "q45" "q46" "q47" "q48" "q49" "q50" "q51"

> modified_q
q42   q42   q43   q43   q44   q44   q45   q45   q46   q46   q47   q48   q49   q50   q51 
"q22" "q32" "q23" "q33" "q24" "q34" "q25" "q35" "q26" "q36" "q27" "q28" "q29" "q30" "q31"

I need to extract from modified_q using duplicated_q with repeated values. This construction is wrong:

> modified_q[duplicated_q]
  q42   q43   q44   q45   q46   q42   q43   q44   q45   q46   q47   q48   q49   q50   q51 
"q22" "q23" "q24" "q25" "q26" "q22" "q23" "q24" "q25" "q26" "q27" "q28" "q29" "q30" "q31" 

How to get vector below?

  q42   q43   q44   q45   q46   q42   q43   q44   q45   q46   q47   q48   q49   q50   q51 
"q22" "q23" "q24" "q25" "q26" "q32" "q33" "q34" "q35" "q36" "q27" "q28" "q29" "q30" "q31" 

CodePudding user response:

You could use pmatch() which has an argument duplicates.ok(default to FALSE) that controls if elements matched against should be used more than once.

modified_q[pmatch(duplicated_q, names(modified_q))]

#   q42   q43   q44   q45   q46   q42   q43   q44   q45   q46   q47   q48   q49   q50   q51
# "q22" "q23" "q24" "q25" "q26" "q32" "q33" "q34" "q35" "q36" "q27" "q28" "q29" "q30" "q31"
  •  Tags:  
  • r
  • Related