Home > Software engineering >  Reorder a vector based on the pattern of another in R?
Reorder a vector based on the pattern of another in R?

Time:06-27

I have a vector nhs_regions. I add the suffix ".upper" and ".lower" to every element of nhs_region in y. I now need to reorder the vector y as per the nhs_regions vector. So I expect the final vector to start with "England.upper", "England.lower", "East of England.upper", "East of england.lower" etc...
Example below:

nhs_regions <- c("England","East of England","London","Midlands","North East and Yorkshire","North West","South East","South West")
x <- c("lower", "upper")
y <- as.vector(outer(nhs_regions, x, paste, sep="."))

CodePudding user response:

This can be corrected if we transpose before concatenating to vector as the unlisting or concatenation to a vector does by column order and not by row. rev reverses the 'x' vector as the original order is in 'lower', 'upper' whereas we want in the reverse order

c(t(outer(nhs_regions, rev(x), paste, sep=".")))

-output

 [1] "England.upper"                  "England.lower"                  "East of England.upper"          "East of England.lower"          "London.upper"                  
 [6] "London.lower"                   "Midlands.upper"                 "Midlands.lower"                 "North East and Yorkshire.upper" "North East and Yorkshire.lower"
[11] "North West.upper"               "North West.lower"               "South East.upper"               "South East.lower"               "South West.upper"              
[16] "South West.lower" 
  • Related