代码之家  ›  专栏  ›  技术社区  ›  Jack Armstrong

从R中的表合并数据帧

  •  0
  • Jack Armstrong  · 技术社区  · 6 年前

    我有几个表可以计算三个数据帧中眼睛颜色的频率。我想我可以在数据帧中转换这些表,然后将它们合并为一个新的数据帧。我认为错误是因为我将表转换成了数据帧,合并似乎增加了表的行数。但我需要:

    Color  Tb1  Tb2   Tb3
    Bl     5    0     3
    Blk    6    7     0
    

    小的情况是不是每个数据帧都有黑色或蓝色的眼睛。所以我需要解释一下,然后把NA改为0。

    我尝试过:

    chart<-merge(tb1,tb2,tb3)
    chart
     Error in fix.by(by.x, x) : 
      'by' must specify one or more columns as numbers, names or logical
    

    chart<-merge(tb1,tb2,tb3,all=T)
    chart
     Error in fix.by(by.x, x) : 
      'by' must specify one or more columns as numbers, names or logical
    

    示例代码:

    one<-c('Black','Black','Black','Black','Black','Black','Blue','Blue','Blue','Blue','Blue')
    two<-c('Black','Black','Black','Black','Black','Black','Black')
    three<-c('Blue','Blue','Blue')
    tb1<-table(one)
    tb2<-table(two)
    tb3<-table(three)
    tb1<-as.data.frame(tb1)
    tb2<-as.data.frame(tb2)
    tb3<-as.data.frame(tb3)
    
    2 回复  |  直到 6 年前
        1
  •  2
  •   OzanStats    6 年前

    bind_rows dplyr

    # creating the setup given in the question
    one<-c('Black','Black','Black','Black','Black','Black','Blue','Blue','Blue','Blue','Blue')
    two<-c('Black','Black','Black','Black','Black','Black','Black')
    three<-c('Blue','Blue','Blue')
    tb1<-table(one)
    tb2<-table(two)
    tb3<-table(three)
    
    # note that there is no need for individual dataframes
    
    # bind the rows of the given tables into a tibble
    result <- dplyr::bind_rows(tb1, tb2, tb3)
    
    # replace NAs with 0 values
    result[is.na(result)] <- 0
    
    # check the resulting tibble
    result
    # # A tibble: 3 x 2
    #   Black  Blue
    #   <dbl> <dbl>
    # 1     6     5
    # 2     7     0
    # 3     0     3
    
        2
  •  1
  •   Carles    6 年前

    newframe <- merge(tb1, tb2, by.x ="one", by.y ="two", all = TRUE)
    merge(newframe, tb3, by.x ="one", by.y ="three", all = TRUE)
    

    dplyr()