1

我有一个数据框,我想在其中分隔 Client.ID 列中的值并融化,因此每一行都包含一个 Client.ID 和相应的 Account.Name 和所有者。

> head(df)
  Account.Owner       Account.Name                   Client.ID
1    Deb Berman     Albertsons LLC      3184, 3186, 3185, 2578
2    Deb Berman        All Recipes                   909, 4937
3    Liz Madsen   American Express                   1230,1236
4    Deb Berman  Bed Bath & Beyond                  1180, 1556
5    Deb Berman           Birchbox 101, 1704, 5149, 5150, 5148
6   Jeff Murphy Brown Shoe Company            5402, 6159, 6160

最后我希望它看起来像这样

Account.Owner       Account.Name                   Client.ID
    1    Deb Berman     Albertsons LLC                  3184  
    2    Deb Berman     Albertsons LLC                  3186
    3    Deb Berman     Albertsons LLC                  3185

谢谢。

4

1 回答 1

4

对于这样的问题,我会建议我的cSplit功能。解决方案变为:

cSplit(mydf, "Client.ID", ",", "long")
#     Account.Owner       Account.Name Client.ID
#  1:    Deb Berman     Albertsons LLC      3184
#  2:    Deb Berman     Albertsons LLC      3186
#  3:    Deb Berman     Albertsons LLC      3185
#  4:    Deb Berman     Albertsons LLC      2578
#  5:    Deb Berman        All Recipes       909
#  6:    Deb Berman        All Recipes      4937
#  7:    Liz Madsen   American Express      1230
#  8:    Liz Madsen   American Express      1236
#  9:    Deb Berman  Bed Bath & Beyond      1180
# 10:    Deb Berman  Bed Bath & Beyond      1556
# 11:    Deb Berman           Birchbox       101
# 12:    Deb Berman           Birchbox      1704
# 13:    Deb Berman           Birchbox      5149
# 14:    Deb Berman           Birchbox      5150
# 15:    Deb Berman           Birchbox      5148
# 16:   Jeff Murphy Brown Shoe Company      5402
# 17:   Jeff Murphy Brown Shoe Company      6159
# 18:   Jeff Murphy Brown Shoe Company      6160

这里使用的参数是:(1) 使用的data.framedata.table,(2) 需要拆分的列,(3) 分隔符,以及 (4) 结果应该是“宽”还是“长” ”。

您可能希望按如下方式对其进行修改:cSplit(mydf, "Client.ID", ", ", "long")或者cSplit(mydf, "Client.ID", ",|,\\s+", "long", fixed = FALSE)取决于您的“Client.ID”列的美观和清洁程度。

这假设我们从以下示例数据集开始:

mydf <- structure(list(Account.Owner = c("Deb Berman", "Deb Berman", 
   "Liz Madsen", "Deb Berman", "Deb Berman", "Jeff Murphy"), 
   Account.Name = c("Albertsons LLC", "All Recipes", "American Express", 
   "Bed Bath & Beyond", "Birchbox", "Brown Shoe Company"), 
   Client.ID = c("3184, 3186, 3185, 2578", "909, 4937", "1230,1236", 
   "1180, 1556", "101, 1704, 5149, 5150, 5148", "5402, 6159, 6160")), 
   .Names = c("Account.Owner", "Account.Name", "Client.ID"), 
   class = c("data.table", "data.frame"), row.names = c(NA, -6L))
于 2014-07-03T20:37:51.537 回答