How to rbind vectors into different columns, leaving NAs in remaining cells

霸气de小男生 提交于 2019-12-11 12:33:47

问题


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:


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


来源:https://stackoverflow.com/questions/29952671/how-to-rbind-vectors-into-different-columns-leaving-nas-in-remaining-cells

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!