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 :
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