0

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!

1 Answer 1

2

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 
Sign up to request clarification or add additional context in comments.

1 Comment

What can one so if the Freq column has repetitions? I mean there can be another row with Freq of 50 and a different seq value.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.