I am trying to place two datasets of 3 columns side by side so that they span 6 columns. They have the same column headings.
How can I place them side by side across the page so that they total 6 columns? As you can see they are different row lengths.
I want to then be able to download them as a single .csv.
I have tried using rbind
, full bind, cbind
, merge
, etc. but nothing seems to work for this very simple task.
CodePudding user response:
You can merge
on the row names by using 0 for the by
argument, then remove the rowname column (i.e., [,-1]
). Then, if you want to have duplicate column names (which is not a good idea), then you can replace the names after merging. Here, I just use subsets of mtcars
as an example.
results <- merge(df1, df2, by = 0, all = TRUE)[,-1]
names(results) <- c(names(df1), names(df2))
Output
mpg cyl disp mpg cyl disp
1 21.0 6 160.0 21.0 6 160
2 21.0 6 160.0 21.0 6 160
3 22.8 4 108.0 22.8 4 108
4 21.4 6 258.0 21.4 6 258
5 18.7 8 360.0 NA NA NA
6 18.1 6 225.0 NA NA NA
7 14.3 8 360.0 NA NA NA
8 24.4 4 146.7 NA NA NA
Data
df1 <- mtcars[1:8, 1:3]
row.names(df1) <- NULL
df2 <- mtcars[1:4, 1:3]
row.names(df2) <- NULL