Search code examples
rreshape2

R -- transform tab delimited string to long format


How to you reshape a string delimited by a tab or space into a long format? The string (called label here) can be of different lengths.

I have this

    var       label
1  work     100 101
2 sleep 500 409 200

and I want this

    var code
1  work  100
2  work  101
3 sleep  500
4 sleep  409
5 sleep  200


# data 
df = data.frame(var = c("work", 'sleep'), label = c('100 101', '500 409 200'))

Solution

  • library(tidyr)
    df %>% 
        separate_rows(label)
    # A tibble: 5 x 2
      var   label
      <chr> <chr>
    1 work  100  
    2 work  101  
    3 sleep 500  
    4 sleep 409  
    5 sleep 200