Home > Enterprise >  is there a method to merge two data frames by country and gender?
is there a method to merge two data frames by country and gender?

Time:11-03

I got two data frames, for example:

one is for males:

country weight
Spain      80
Germany    70
Italy      60

and the other one is for females:

country weight
Spain      65
Germany    70
Italy      60

Now I want to merge them and make them look like that:

country gender   weight
Spain         m      80
Spain         f      65
Germany       m      70
Germany       f      70
Italy         m      60
Italy         f      60

I hopes the example makes My problem clear.

Thank you

CodePudding user response:

Try this

countries <- c("Spain", "Germany", "Italy")

weights <- c(80, 70, 60)
dfMale <- cbind(data.frame(countries), data.frame(weights))
dfMale$Gender <- "m"


weights <- c(65,70,60)
dfFemale <- cbind(data.frame(countries), data.frame(weights))
dfFemale$Gender <- "f"

newdf <- rbind(dfMale,dfFemale)
  • Related