Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Create a dataframe from two vectors of unequal length in R

I have two vectors of unequal length. Let’s call them group1 and group2.

group1 <- c(1,2,3)
group2 <- c(6,7,8,9,10)

I want to create a dataframe like:

key value
group1 1
group2 6
group2 7
group1 2

…So on

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I know how to do it if the length of the vectors is the same: just create a tibble and then gather it.
But what to do in this case?

>Solution :

You may try

group1 <- 1:3
group2 <- 6:10
n <- length(group2) - length(group1)
group1 <- c(group1, rep(NA, n))

tibble(group1,group2) %>%
  rownames_to_column("idx") %>%
  gather(group1,group2, key = 'key', value = 'value') %>%
  mutate(idx = as.numeric(idx)) %>%
  mutate(idx = ifelse(key == 'group1', floor(idx/2), floor((idx-1)/2))) %>%
  arrange(idx, key) %>%
  na.omit %>% select(-idx)


  key    value
  <chr>  <int>
1 group1     1
2 group2     6
3 group2     7
4 group1     2
5 group1     3
6 group2     8
7 group2     9
8 group2    10
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading