Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

combine vectors of different length into data frame in R

Tags:

r

I have four vectors as follows:

x1=letters[1:5]
x2=c("a","b","c")
x3=c("a","b","c","d")
x4=c("a","b","e")

Actually,I want to get a data frame like this:

 data.frame(x1,x2=c("a","b","c",NA,NA),
            x3=c("a","b","c","d",NA),
           x4=c("a","b",NA,NA,"e"))
  x1   x2   x3   x4
1  a    a    a    a
2  b    b    b    b
3  c    c    c <NA>
4  d <NA>    d <NA>
5  e <NA> <NA>    e

Could someone help me or give me a function as indicators?

like image 880
chunjin Avatar asked Nov 21 '25 08:11

chunjin


1 Answers

There's a non-exported function charMat in my "splitstackshape" package that might be useful for something like this.

Here, I've used it in conjunction with mget:

## library(splitstackshape) # not required since you'll be using ::: anyway...
data.frame(t(splitstackshape:::charMat(mget(ls(pattern = "x\\d")), mode = "value")))
#   X1   X2   X3   X4
# a  a    a    a    a
# b  b    b    b    b
# c  c    c    c <NA>
# d  d <NA>    d <NA>
# e  e <NA> <NA>    e
like image 128
A5C1D2H2I1M1N2O1R2T1 Avatar answered Nov 23 '25 23:11

A5C1D2H2I1M1N2O1R2T1



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!