Sia
Sia

Reputation: 43

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!

Upvotes: 0

Views: 749

Answers (1)

jdobres
jdobres

Reputation: 11957

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 

Upvotes: 2

Related Questions