0
votes

I have two tibbles: the first one with more than one row and second one, with exactly one row.

I want to col bind them, and, for this purpose, I want the second one to have the same number of rows as the first.

I can do this operation with this trick:

for (i in colnames(df2)) {
  df1[[i]] <- df2[1,i]
}

However, this sounds like a workaround to me. Is there a "tidier" way of doing this (I mean, with tidyverse)?

1
just cbind(df1,df2)HubertL

1 Answers

1
votes

You can just go for cbind(df1,df2), it will expand the shortest data.frame to match the number of rows of the longest

If you want to use dplyr, you would want a cross join... but dplyr has no cross join yet.

You can create a dummy column on both tables, and inner_join on it:

df1 %>% 
  mutate(dummy_id=1) %>% 
  inner_join(df2 %>% mutate(dummy_id=1)) %>% 
  mutate(dummy_id=NULL)