r, cbind two columns, values in specifi order

348 Views Asked by At

I have 2 lists, one with Gender c('m', 'f', 'f', 'm', 'f'), the other with names c('Peter', 'Peter', 'Anna', 'Anna', 'Peter'). I want to join / merge the two columns to a data frame, where the sex-values are suitable to the names (Peter with m, Anna with f).

How to I do this in R?

Thanks for helping guys!

2

There are 2 best solutions below

0
On

Suppose you have the following two lists:

gender = list(c('m', 'f', 'f', 'm', 'f'))
names = list(c('Peter', 'Peter', 'Anna', 'Anna', 'Peter'))
 

One option would be to use unlist and combine them into a data.frame:

data.frame(names = unlist(names),
           gender = unlist(gender)
           )

#   names gender
# 1 Peter     m
# 2 Peter     f
# 3 Anna      f
# 4 Anna      m
# 5 Peter     f
        
0
On

Another option with unnest

library(dplyr)
library(tidyr)
tibble(gender, names) %>%
    unnest(c(gender, names))

data

gender <- list(c('m', 'f', 'f', 'm', 'f'))
names <- list(c('Peter', 'Peter', 'Anna', 'Anna', 'Peter'))