Home > Blockchain >  Create a dataframe combining unequal vectors
Create a dataframe combining unequal vectors

Time:05-19

I am trying to create a dataframe by combining all the vectors that I got by exttracting column with specific match as below:

a <-filter(data, Strain == "9.2.1") %>% pull(gr)
b <-filter(data, Strain == "4.2.1") %>% pull(gr)
c <-filter(data, Strain == "4.2.2") %>% pull(gr)

The problem is all the vectors are of diffrent length:

a is num[1:7]
b is  num[1:5]
c is num[1:12]

I used the code to create dataframe data.frame(a,b,c) and got error: differing number of rows.

Looking forward to suggestions

CodePudding user response:

Put all the vectors in a list, then do the following

mylist <- list(a=a, b=b, c=c)
mx <- max(lengths(mylist))

data.frame(lapply(list(a=a, b=b, c=c), `length<-`, mx))
    a  b  c
1   1  1  1
2   2  2  2
3   3  3  3
4   4  4  4
5   5  5  5
6   6 NA  6
7   7 NA  7
8  NA NA  8
9  NA NA  9
10 NA NA 10
11 NA NA 11
12 NA NA 12
  •  Tags:  
  • r
  • Related