wussyx
wussyx

Reputation: 85

How do I join multiple unrelated datasets

In R, I'm trying to join 5 datasets together which do not have any common column.

An example would be to join mtcars, cars and iris datasets together. How do I go about?

Using dplyr's

full_join(mtcars, cars, iris)

returns an error where it tells me by must be a (named) character vector. However I have no common column to use for 'by = '

library(dplyr)
full_join(mtcars, cars, iris)

I would like all 3 datasets to be side by side, rows which have no data will be NA.

Upvotes: 2

Views: 211

Answers (1)

akrun
akrun

Reputation: 886958

If we want to cbind, then use cbind.fill

library(rowr)
cbind.fill(mtcars, cars, iris, fill = NA)

The dataset dimensions are not the same, the fill = NA will fill those datasets that have less number of rows with NA at the end


Or using tidyverse, keep the datasets in a list, add row names as a column by looping through the list and reduce to a single dataset joining by the 'rowname'

library(tidyverse)
list(mtcars, cars, iris) %>%
     map(~ as_tibble(.x) %>%
              rownames_to_column) %>% 
     reduce(full_join, by = 'rowname')

Upvotes: 2

Related Questions