Использование cbind возвращает неожиданные результаты - PullRequest
1 голос
/ 27 февраля 2020

У меня есть тиббл ab c и тиббл. Def.

ab c

# 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.

Я хочу сделать аб c и def, чтобы получить тиббл с 6 столбцами.

Но когда я делаю cbind (ab c, def), я получаю следующее. Я не уверен почему. Может кто-нибудь помочь?

       abc         def      
Category Character,4 Numeric,4
Measure  Character,4 Numeric,4
Date     Numeric,4   Numeric,4
Value    Numeric,4   Numeric,4

Ответы [ 2 ]

4 голосов
/ 27 февраля 2020
new_tibble <- bind_cols(abc,def)
3 голосов
/ 27 февраля 2020

В структуре один из них сгруппирован с атрибутами группы, поэтому если мы ungroup или преобразуем в data.frame (as.data.frame - удаляет атрибуты), cbind будет работать

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

Может быть воспроизведено с 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

Без атрибутов группы

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

Также, проверяя methods для cbind

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

при наличии grouped_df он автоматически вызывает cbind.grouped_df вместо cbind.data.frame. Если мы явно укажем cbind.data.frame, он должен работать

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

ПРИМЕЧАНИЕ. Вопрос ОП касался поведения с cbind, и это отвечает его причине

...