split a column in a sequential array of names

16 Views Asked by At

Good evening community, I want to separate a character column of the separate_wider_delim type into several sequential columns.

"count_id"

"120 987 203 116 77 890 194 88 915 926 1028 190 452 916 891 456 904 965 404 11 977 414 119 659 52 406 94 128 459 145 635 453 426 405 880 543 121 803 1035 98 87 337 425 43 608 496 418 202 745 252 "

"987 120 203 456 414 404 452 194 119 190 890 406 116 11 459 926 426 453 405 891 77 915 904 916 52 425 659 965 1028 94 418 458 88 128 417 977 880 608 202 145 610 543 427 428 639 121 43 227 98 450 "

"120 987 203 452 456 116 404 414 77 890 194 406 926 915 88 1028 190 459 916 891 426 904 977 453 405 965 11 52 659 425 418 94 128 635 496 417 119 145 458 543 880 1035 803 450 121 428 87 337 427 98 "

This is my column of characters that I want to separate into several items sequentially as it appears here How to separate several columns

I have used gsub, str_replace_all and other methods but have not been able to ungroup the column into multiple columns, with no satisfactory results.

1

There are 1 best solutions below

0
Mark On

Assuming the data is like this:

df <- data.frame(
    count_id = c("120 987 203 116 77 890 194 88 915 926 1028 190 452 916 891 456 904 965 404 11 977 414 119 659 52 406 94 128 459 145 635 453 426 405 880 543 121 803 1035 98 87 337 425 43 608 496 418 202 745 252 ", "987 120 203 456 414 404 452 194 119 190 890 406 116 11 459 926 426 453 405 891 77 915 904 916 52 425 659 965 1028 94 418 458 88 128 417 977 880 608 202 145 610 543 427 428 639 121 43 227 98 450 ", "120 987 203 452 456 116 404 414 77 890 194 406 926 915 88 1028 190 459 916 891 426 904 977 453 405 965 11 52 659 425 418 94 128 635 496 417 119 145 458 543 880 1035 803 450 121 428 87 337 427 98 "))

You can do this:

tidyr::separate_wider_delim(df, count_id, delim = " ", names_sep = "_")

# Output:
# A tibble: 3 × 51
  count_id_1 count_id_2 count_id_3 count_id_4 count_id_5 count_id_6 count_id_7
  <chr>      <chr>      <chr>      <chr>      <chr>      <chr>      <chr>     
1 120        987        203        116        77         890        194       
2 987        120        203        456        414        404        452       
3 120        987        203        452        456        116        404       
# ℹ 44 more variables: count_id_8 <chr>, count_id_9 <chr>, count_id_10 <chr>,
#   count_id_11 <chr>, count_id_12 <chr>, count_id_13 <chr>, count_id_14 <chr>,
#   count_id_15 <chr>, count_id_16 <chr>, count_id_17 <chr>, count_id_18 <chr>,
#   count_id_19 <chr>, count_id_20 <chr>, count_id_21 <chr>, count_id_22 <chr>,
#   count_id_23 <chr>, count_id_24 <chr>, count_id_25 <chr>, count_id_26 <chr>,
#   count_id_27 <chr>, count_id_28 <chr>, count_id_29 <chr>, count_id_30 <chr>,
#   count_id_31 <chr>, count_id_32 <chr>, count_id_33 <chr>, …