Home > Mobile >  Combine similar columns with different character names data?
Combine similar columns with different character names data?

Time:02-13

ID <- c("IDa", "IDb","IDc","IDe","IDd","IDe")
names1 <- c("robin", "bob", "eric", "charlie", "robin", "gabby")
matrix1 <- matrix(names1, 1, 6)
colnames(matrix1) <- c("IDa", "IDb", "IDc","IDe", "IDd", "IDe")


This is the output:

IDa IDb IDc IDe IDd IDe
robin bob eric charlie robin gabby

But I want it to look like this:

IDa IDb IDc IDe IDd
robin bob eric charlie robin
gabby

CodePudding user response:

We may split and then cbind after padding with NA

lst1 <- split(names, ID)
do.call(cbind, lapply(lst1, `length<-`, max(lengths(lst1))))

-output

     IDa     IDb   IDc    IDd     IDe      
[1,] "robin" "bob" "eric" "robin" "charlie"
[2,] NA      NA    NA     NA      "gabby"  

CodePudding user response:

Another option:

library(reshape2)
library(tidyverse)

melt(matrix1) %>% 
  select(-Var1) %>% 
  group_by(Var2) %>% 
  mutate(id = row_number()) %>% 
  pivot_wider(
    names_from = Var2,
    values_from = value
  ) %>% 
  select(-id)
  IDa   IDb   IDc   IDe     IDd  
  <chr> <chr> <chr> <chr>   <chr>
1 robin bob   eric  charlie robin
2 NA    NA    NA    gabby   NA   
  • Related