cbind 用法 returns 意外结果

cbind usage returns unexpected results

我有一个 tibble abc 和一个 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.

我想 cbind abc 和 def 以获得 6 列的 tibble。

但是当我执行 cbind(abc,def) 时,我得到以下信息。我不确定为什么。有人可以帮忙吗?

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

在结构中,其中一个是用组属性分组的,所以如果我们 ungroup 或转换为 data.frameas.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

注意:OP 的问题是关于 cbind 的行为,这回答了它的原因

new_tibble <- bind_cols(abc,def)