R semicolon delimited a column into rows

后端 未结 3 1794
独厮守ぢ
独厮守ぢ 2020-11-29 13:43

I am using RStudio 2.15.0 and have created an object from Excel using XLConnect with 3000+ rows and 12 columns I am trying to delimit/split a column into the rows but don\'t

3条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-29 14:20

    Here's a quick data.table possible solution

    library(data.table)
    unique(setDT(df)[, .(PolId = unlist(strsplit(as.character(PolId), ";"))), by = Description])
    #    Description  PolId
    # 1:       TEST1 ABC123
    # 2:       TEST1 ABC456
    # 3:       TEST1 ABC789
    # 4:       TEST1 AAA123
    # 5:       TEST2 AAA123
    # 6:       TEST3 ABB123
    # 7:       TEST3 ABC123
    

    Per your edit- Another option (in case you have more than two columns)

    library(splitstackshape)
    unique(cSplit(df, "PolId", ";", "long"))
    #     PolId Description Document.Type
    # 1: ABC123       TEST1          Pol1
    # 2: ABC456       TEST1          Pol1
    # 3: ABC789       TEST1          Pol1
    # 4: AAA123       TEST1          End1
    # 5: AAA123       TEST2          End2
    # 6: ABB123       TEST3          End1
    # 7: ABC123       TEST3          End1
    

提交回复
热议问题