【问题标题】:Pivot a string by delimiter按分隔符旋转字符串
【发布时间】:2022-11-03 01:58:01
【问题描述】:

我有一个字符串:

Hallux  OtherToes  Transmetatarsal  Forefoot  BelowKnee  SkewFlap  ThroughKnee  AboveKnee  Other  YN.

我想把它变成一个长格式的小标题或数据框,有两列,除了最后一个值之外的每个值都是每行,最后一列重复:

  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. 

【问题讨论】:

    标签: r stringr


    【解决方案1】:
    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.
    

    【讨论】:

      【解决方案2】:
      head(within(data.frame(variable = scan(text = str1, what = "",
           quiet = TRUE)), format_id <- variable[length(variable)]),-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.
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-11-24
        • 2019-08-23
        • 2010-10-19
        • 2020-10-03
        • 1970-01-01
        • 1970-01-01
        • 2011-06-09
        相关资源
        最近更新 更多