How to rbind vectors into different columns, leavi

2019-07-29 11:49发布

Let's say I have an unspecified number of vectors of different lengths, and I want to effectively rbind them together, with the caveat that they must each occupy a different column in the resulting data.frame. You may assume that the vectors are contained in a list, but you cannot depend on any component names that may be defined within the list.

Below I present a random sample input (lv) and a poor solution to generate the required output that manually builds the resulting data.frame by repeating NA and combining each input vector by name.

set.seed(1);
lv <- list(a=sample(30,5),b=sample(30,3),c=sample(30,7),d=sample(30,2));
lv;
## $a
## [1]  8 11 17 25  6
##
## $b
## [1] 27 28 19
##
## $c
## [1] 19  2  6  5 18 10 30
##
## $d
## [1] 15 21
##
with(lv,data.frame(a=c(a,rep(NA,length(b)+length(c)+length(d))),b=c(rep(NA,length(a)),b,rep(NA,length(c)+length(d))),c=c(rep(NA,length(a)+length(b)),c,rep(NA,length(d))),d=c(rep(NA,length(a)+length(b)+length(c)),d)));
##     a  b  c  d
## 1   8 NA NA NA
## 2  11 NA NA NA
## 3  17 NA NA NA
## 4  25 NA NA NA
## 5   6 NA NA NA
## 6  NA 27 NA NA
## 7  NA 28 NA NA
## 8  NA 19 NA NA
## 9  NA NA 19 NA
## 10 NA NA  2 NA
## 11 NA NA  6 NA
## 12 NA NA  5 NA
## 13 NA NA 18 NA
## 14 NA NA 10 NA
## 15 NA NA 30 NA
## 16 NA NA NA 15
## 17 NA NA NA 21

Note: You don't have to use rbind(), I just felt that that was the clearest way to introduce the problem. Another way of thinking about this is I want to cbind() vectors into different (never overlapping) rows.

1条回答
神经病院院长
2楼-- · 2019-07-29 12:00

Try

library(reshape2)
library(data.table)
dcast(setDT(melt(lv))[, rn:=.I], rn~L1, value.var='value')

Or

dcast(setDT(melt(lv), keep.rownames=TRUE), 
                  as.numeric(rn)~L1, value.var='value')

Or as suggested by @David Arenburg

recast(lv, seq_along(unlist(lv)) ~ L1)

Or using base R

d1 <- stack(lv)
reshape(transform(d1, rn=1:nrow(d1)), idvar='rn',
                         timevar='ind', direction='wide')
查看更多
登录 后发表回答