Home > Blockchain >  Pivot a string by delimiter
Pivot a string by delimiter

Time:11-03

I have a string:

Hallux  OtherToes  Transmetatarsal  Forefoot  BelowKnee  SkewFlap  ThroughKnee  AboveKnee  Other  YN.

I want to turn it into a tibble or dataframe in long format with two columns, where each value except the last is per row and the last column is repeated:

  variable        format_id
  <chr>           <chr>    
1 Hallux          YN.      
2 OtherToes       YN.      
3 Transmetatarsal YN.      
4 Forefoot        YN.      
5 BelowKnee       YN.      
6 SkewFlap        YN.      
7 ThroughKnee     YN.      
8 AboveKnee       YN.      
9 Other           YN. 

CodePudding user response:

s <- 'Hallux  OtherToes  Transmetatarsal  Forefoot  BelowKnee  SkewFlap  ThroughKnee  AboveKnee  Other  YN.'
s <- strsplit(s, '\\s ')[[1]]
data.frame(variable=head(s, -1),
           format_id=tail(s, 1))

#          variable format_id
# 1          Hallux       YN.
# 2       OtherToes       YN.
# 3 Transmetatarsal       YN.
# 4        Forefoot       YN.
# 5       BelowKnee       YN.
# 6        SkewFlap       YN.
# 7     ThroughKnee       YN.
# 8       AboveKnee       YN.
# 9           Other       YN.

CodePudding user response:

Using scan.

scan(t=x, w='A', qui=T) |> {\(x) data.frame(variable=x[-length(x)], format_id=x[length(x)])}()
#          variable format_id
# 1          Hallux       YN.
# 2       OtherToes       YN.
# 3 Transmetatarsal       YN.
# 4        Forefoot       YN.
# 5       BelowKnee       YN.
# 6        SkewFlap       YN.
# 7     ThroughKnee       YN.
# 8       AboveKnee       YN.
# 9           Other       YN.

Data:

x <- 'Hallux  OtherToes  Transmetatarsal  Forefoot  BelowKnee  SkewFlap  ThroughKnee  AboveKnee  Other  YN.'
  • Related