Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Keep the order of rows of column of merged data frame the same as the rows of the common column of the 2 initial dataframes

I have 2 dataframes which I merge based ona a common column. What I want is the order of the rows of the new dataframe to be first the order of alltr Attribute Name and then the one of allev.Not in alphabetical order and not having to set the order manually after merging. So the order of the Attribute Name column in the new one should be Age, Gender, Income, Area

# Sample dataframes
alltr <- data.frame(
  `Attribute Name` = c("Age", "Gender"),
  Value_x = c(254, 100)
)

allev <- data.frame(
  `Attribute Name` = c("Income", "Area"),
  Value_y = c(708, 500)
)

# Merging the dataframes
merged_df2 <- merge(alltr, allev, by = "Attribute Name", all = TRUE)

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

merge() has a sort argument, so you can do:

merge(alltr, allev, by = "Attribute.Name", all = TRUE, sort = FALSE)

  Attribute.Name Value_x Value_y
1            Age     254      NA
2         Gender     100      NA
3         Income      NA     708
4           Area      NA     500

Alternatively, you can use dplyr::full_join():

dplyr::full_join(alltr, allev, by = "Attribute.Name")

  Attribute.Name Value_x Value_y
1            Age     254      NA
2         Gender     100      NA
3         Income      NA     708
4           Area      NA     500
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading