如何在r中的多个数据帧上应用dcast

时间:2017-09-21 11:02:24

标签: r

我在r中有31个数据帧,从df1到df31

df1

make   type    qty

df2

make   type    qty
abc    def     10
dde    ert     3 

df3

make   type    qty
rty    r45      78

我想将其播放到以下

make   type    qty    make_1    type_1    qty_1   
 NA     NA      NA     NA        NA        NA       
 abc    def     10     dde       ert       3 
 rty    r45     78     NA        NA        NA

如何在r?

中为所有数据帧一起完成

这是我的数据框架结构

  dput(dredge_cutter1)
  structure(list(Make = character(0), Type = character(0), Qty. = 
  numeric(0)), .Names = c("Make", 
  "Type", "Qty."), row.names = integer(0), class = "data.frame")
  > dput(dredge_cutter5)
  structure(list(Make = "SHRIYAM", Type = "FLARRED", Qty. = 3), .Names = 
  c("Make", 
  "Type", "Qty."), row.names = 2L, class = "data.frame")
  > dput(dredge_cutter23)
  structure(list(Make = c("SHRIYAM", "SHRIYAM"), Type = c("FLARED", 
  "CHISEL POINT"), Qty. = c(15, 2)), .Names = c("Make", "Type", 
   "Qty."), row.names = 2:3, class = "data.frame")

1 个答案:

答案 0 :(得分:0)

一个选项是

library(data.table)
res <- rbindlist(lapply(mget(paste0("df", 1:3)), function(x) {
   x <- if(nrow(x)==0) data.frame(setNames(replicate(3, NA, simplify = FALSE),
      names(x))) else x
     dcast(as.data.table(x)[, n := seq_len(.N)],
          1~n, value.var = c("Make", "Type", "Qty."))}),
          fill = TRUE)[,-1, with = FALSE]


setnames(res, make.unique(sub("_\\d+", "", names(res)), sep="_"))[]
#      Make    Type Qty.  Make_1       Type_1 Qty._1
#1:      NA      NA   NA      NA           NA     NA
#2: SHRIYAM FLARRED    3      NA           NA     NA
#3: SHRIYAM  FLARED   15 SHRIYAM CHISEL POINT      2