简体   繁体   中英

Combine similar columns with different character names data?

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

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"  

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   

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM