简体   繁体   中英

split column containing strings of unequal length into multiple columns in R

I have a data frame like this -

uniq = data.frame(Freq = c(172,4,50,3), 
  seq = c("G","G G T G T","G G T T","T G T T A T T"))

I want to split the second column into multiple columns without any repetitions. The string in separated by spaces.

I tried using the code below but this duplicates values from smaller string to the length of the longer string -

within(uniq, uniq_seq <-data.frame(do.call('rbind', strsplit(as.character(uniq[,2]), ' ')))) 

Thanks for your help!

Definitely an odd request, but definitely possible with tidyverse .

library(tidyverse)

df <- uniq %>% 
  mutate(n = row_number()) %>%
  separate_rows(seq, sep = ' ') %>% 
  group_by(n, Freq) %>% 
  mutate(n2 = row_number()) %>% 
  spread(n2, seq) %>%
  select(-n)

   Freq `1`   `2`   `3`   `4`   `5`   `6`   `7`  
  <dbl> <chr> <chr> <chr> <chr> <chr> <chr> <chr>
1     3 T     G     T     T     A     T     T    
2     4 G     G     T     G     T     NA    NA   
3    50 G     G     T     T     NA    NA    NA   
4   172 G     NA    NA    NA    NA    NA    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