【问题标题】:How to get all possible orders of comma separated strings如何获取逗号分隔字符串的所有可能顺序
【发布时间】:2017-09-11 07:04:05
【问题描述】:

我尝试搜索 R 问题,但找不到任何有用的东西。

我有一个这样的数据框:

Post_ID New_Mentions_1      New_Mentions_2
   1          model                      
   2      telephone          louis vuitton
   3           uber          employee
   4   united states                      
   5          onion         pepper, rice, garlic

我的预期结果是使用 New_Mention_2 的所有可能顺序扩展数据框

 Post_ID New_Mentions_1      New_Mentions_2
   1          model                      
   2      telephone           louis vuitton
   3           uber            employee
   4   united states                      
   5          onion        pepper,rice,garlic
   5          onion        rice,garlic,pepper
   5          onion        garlic,pepper,rice
   5          onion        pepper,garlic,rice
   5          onion        garlic,rice,pepper
   5          onion        rice,pepper,garlic

请帮我设计一个程序。我也有几行用逗号分隔的 5 个关键字。

【问题讨论】:

  • 这是一个奇怪的要求。为什么需要这些项目的所有可能排列?

标签: r algorithm dataframe permutation


【解决方案1】:

应该有更简单的方法来处理这个问题,但我似乎找不到。

为了确保我们讨论的是同一个数据框,我重新发布您的数据:

df <- structure(list(New_Mentions_1 = c("model", "telephone", "uber", 
        "united_states", "onion"), New_Mentions_2 = c(NA, "louis_vuitton", 
        "employee", NA, "pepper,rice,garlic")), .Names = c("New_Mentions_1", 
        "New_Mentions_2"), class = "data.frame", row.names = c(NA, -5L))

首先使用grep 检查df 中的哪些行在New_Mentions_2 列中有多个值。此函数返回第二列包含逗号值的行。然后我们将数据框拆分到不需要修复的部分(即第二列中没有逗号值)并命名为newdf。需要修复的部分称为subdf

我们将使用subdf 进行一些处理(代码下方的详细信息)以获取所有可能的值组合并将结果附加到newdf 数据框:

library(gtools)
# Which rows in df have multiple values in the second column?
inds <- grep(pattern = ",", df$New_Mentions_2)

subdf <- df[inds, ]
newdf <- df[-inds, ]

# Just in case you have multiple 'problematic' rows, we'll loop through all of them
for(i in 1:nrow(subdf)){
  splitted <- strsplit(subdf$New_Mentions_2[i], ", ")[[1]]
  n        <- length(splitted)
  shuffled <- permutations(n, n)
  for(j in 1:nrow(shuffled)){
    val_2 <- paste(splitted[shuffled[j, ]], collapse = ", ")
    val_1 <- subdf$New_Mentions_1[i]
    newdf <- rbind(newdf, c(val_1, val_2))
  }
}

“乱七八糟”部分主要在外循环中执行。首先,例如的价值每个,(逗号+空格)都会拆分“胡椒、米饭、大蒜”。然后splitted 将包含c("pepper", "rice", "garlic"),我们使用gtools 包中的permutations 函数获得所有可能的组合。在内循环的第一行,打乱的字符串将重新组合成一个字符串(paste()collapse = ", ") 参数),以便我们可以再次将它们放入数据框的一列中。

【讨论】:

    猜你喜欢
    • 2012-05-19
    • 2019-08-25
    • 2011-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-11
    相关资源
    最近更新 更多