1

I have a tibble abc and a tibble def.

abc

# A tibble: 4 x 4
# Groups:   Category, Measure [1]
  Category Measure     Date          Value
  <chr>    <chr>       <date>        <dbl>
1 Pickles  Gross Sales 2016-01-03 6518758.
2 Pickles  Gross Sales 2016-01-10 5640691.
3 Pickles  Gross Sales 2016-01-17 5450121.
4 Pickles  Gross Sales 2016-01-24 5726041.

def

# A tibble: 4 x 2
        all       pb
      <dbl>    <dbl>
1 25992010. 4836410.
2 25769111. 4692100.
3 25612548. 4555298.
4 23869990. 4180362.

I want to cbind abc and def to get a tibble with 6 columns.

But when I do cbind(abc,def) I get the below. I am not sure why. Can someone help?

       abc         def      
Category Character,4 Numeric,4
Measure  Character,4 Numeric,4
Date     Numeric,4   Numeric,4
Value    Numeric,4   Numeric,4
user17144
  • 428
  • 3
  • 18

2 Answers2

4
new_tibble <- bind_cols(abc,def)
Maurits Evers
  • 49,617
  • 4
  • 47
  • 68
3

In the structure, one of them is grouped with group attributes so we if we ungroup or convert to data.frame (as.data.frame - removes the attributes), cbind would work

library(dplyr)
abc %>%
   ungroup %>%
   cbind(def)

It can be reproduced with mtcars

cbind(as_tibble(head(mtcars[1:4], 3)) %>% 
       group_by(cyl), 
       as_tibble(head(mtcars[5:7], 3)))
#     [,1]      [,2]     
#mpg  Numeric,3 Numeric,3
#cyl  Numeric,3 Numeric,3
#disp Numeric,3 Numeric,3
#hp   Numeric,3 Numeric,3

Without group attributes

cbind(as_tibble(head(mtcars[1:4], 3)), as_tibble(head(mtcars[5:7], 3)))
#   mpg cyl disp  hp drat    wt  qsec
#1 21.0   6  160 110 3.90 2.620 16.46
#2 21.0   6  160 110 3.90 2.875 17.02
#3 22.8   4  108  93 3.85 2.320 18.61

Also, by checking the methods for cbind

methods("cbind")
#[1] cbind.data.frame  cbind.grouped_df* cbind.ts*  

when there is a grouped_df, it automatically calls the cbind.grouped_df instead of cbind.data.frame. If we explicitly specify cbind.data.frame, it should work

cbind.data.frame(as_tibble(head(mtcars[1:4], 3)) %>% 
       group_by(cyl), 
        as_tibble(head(mtcars[5:7], 3)))
#   mpg cyl disp  hp drat    wt  qsec
#1 21.0   6  160 110 3.90 2.620 16.46
#2 21.0   6  160 110 3.90 2.875 17.02
#3 22.8   4  108  93 3.85 2.320 18.61

NOTE: The OP's question was about the behavior with cbind and this answers the cause of it

akrun
  • 874,273
  • 37
  • 540
  • 662
  • Thank you. How did you know it was grouped? Is there any function call to know whether a data frame is grouped? – user17144 Feb 27 '20 at 03:19
  • 1
    @user2371765 it is already showed in your post `# Groups: Category, Measure [1]` – akrun Feb 27 '20 at 17:32