简体   繁体   English

如何在R中的多个数据帧上应用Dcast

[英]how to apply dcast on multiple dataframes in r

I have 31 dataframes in r from df1 to df31 我从df1到df31有31个数据帧

df1

make   type    qty

df2

make   type    qty
abc    def     10
dde    ert     3 

df3

make   type    qty
rty    r45      78

I want to dcast it to following 我想抛弃到下面

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

How can I do it for all dataframes together in r ? 如何在r中对所有数据帧一起执行此操作?

This is my dataframe structure 这是我的数据框结构

  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")

One option would be 一种选择是

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM