Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write two vectors of different length into one data frame by writing same values into same row?

I want to write two vectors of different length with partly equal values into one data frame. The same values should be written in the same row.

ef1 <- c('A1', 'A2', 'B0', 'B1', 'C1', 'C2')
ef2 <- c('A1', 'A2', 'C1', 'C2', 'D1', 'D2')

If I write them in one data frame, it looks like this:

df <- data.frame (ef1, ef2)
> df
  ef1 ef2
1  A1  A1
2  A2  A2
3  B0  C1
4  B1  C2
5  C1  D1
6  C2  D2

But what I want is this:

> df
  ef1 ef2
1  A1  A1
2  A2  A2
3  B0  NA
4  B1  NA
5  C1  C1
6  C2  C2
7  NA  D1
8  NA  D2

I'm grateful for any help.

like image 599
phiaba Avatar asked Jul 14 '20 10:07

phiaba


People also ask

Can you add two vectors of different lengths?

The individual numbers that make up a vector are called elements or components of the vector. and vector addition. Two vectors of the same size (i.e. number of elements) can be added: this adds the corresponding elements to create a new vector of the same size. You can't add two vectors of different sizes.


2 Answers

One option is match

(tmp <- unique(c(ef1, ef2)))
# [1] "A1" "A2" "B0" "B1" "C1" "C2" "D1" "D2"

out <- data.frame(ef1 = ef1[match(tmp, ef1)],
                  ef2 = ef2[match(tmp, ef2)])

Result

out
#   ef1  ef2
#1   A1   A1
#2   A2   A2
#3   B0 <NA>
#4   B1 <NA>
#5   C1   C1
#6   C2   C2
#7 <NA>   D1
#8 <NA>   D2
like image 74
markus Avatar answered Oct 08 '22 23:10

markus


Another solution, using dplyr's full_join. The idea is to artificially create a merging column and then make a full join.

ef1<-tibble(a=ef1,ef1=ef1)
ef2<-tibble(a=ef2,ef2=ef2)

ef1 %>% 
  full_join(ef2,by="a") %>% 
  select(ef1,ef2)

# A tibble: 8 x 2
  ef1   ef2  
  <chr> <chr>
1 A1    A1   
2 A2    A2   
3 B0    NA   
4 B1    NA   
5 C1    C1   
6 C2    C2   
7 NA    D1   
8 NA    D2 
like image 26
Maël Avatar answered Oct 08 '22 21:10

Maël