【问题标题】:Combination in R [duplicate]R中的组合[重复]
【发布时间】:2017-07-03 18:55:19
【问题描述】:

如何编写一个逻辑来显示所有可能的“N”位组合 “A”和“B”,其中“A”和“B”形成一对,只有当我们已经有一个非成对的“A”时才能插入“B”。

例如:

when N=2, output should be ["AB"]   
when N=4, output should be ["AABB","ABAB"]  
when N=6, output should be ["AAABBB","AABBAB","AABABB","ABABAB","ABAABB"]

【问题讨论】:

  • 你试过什么?另外,你能解释更多吗?我不明白您所说的“形成一对”(A 和 B 的数量相等?)或“非配对 A”是什么意思。为什么 n = 4 输出中不包含“ABBA”、“BAAB”、“BABA”、“BBAA”?
  • 完全迷失了这个问题..
  • 据我了解,如果之前的 As 多于 B,则只能添加 B(即,有一个 A 还没有 B“伙伴”)。这就是为什么 BBAA 和 BABA 和 BAAB 不起作用,因为第一个 B 没有“未配对”A。@mak,你能确认并澄清你原来的帖子吗?
  • @zx8754 这似乎大部分是正确的,但为什么“AABABB”有效?
  • 这是我的猜测:(1) 将{N = 2} => {"AB"} 视为基本情况。 (2) 对于 N > 2,反复思考。您可以将 "AB" 插入到任何 {N - 2} 集合中(i)在字符串的开头,(ii)在字符串中的任何 A 之后,或(iii)在字符串的末尾。

标签: r combinations


【解决方案1】:

我相信这应该可以满足您的需求。

# Number of combinations
n <- 6

# Create dataframe of all combinations for 1 and -1 taken n number of times
# For calculations 1 = A and -1 = B
df <- expand.grid(rep(list(c(1,-1)), n))

# Select only rows that have 1 as first value
df <- df[df[,1] == 1,]

# Set first value for all rows as "A"
df[,1] <- "A"

# Set value for first calculation column as 1
df$s <- 1

# Loop through all columns starting with 2
for(i in 2:n){
  # Get name of current column
  cur.col <- colnames(df)[i]

  # Get the difference between the number of 1 and -1 for current column and the running total
  df$s2 <- apply(df[,c(cur.col,"s")], 1, sum)

  # Remove any rows with a negative value
  df <- df[df$s2 >= 0,]

  # Set running total to current total
  df$s <- df$s2

  # Set values for current column
  df[,i] <- sapply(as.character(df[,i]), switch, "1" = "A", "-1" = "B")

  # Check if current column is last column
  if(i == n){
    # Only select rows that have a total of zero, indicating that row has a pairs of AB values
    df <- df[df$s2 == 0, 1:n]
  }
}

# Get vector of combinations
combos <- unname(apply(df[,1:n], 1, paste0, collapse = ""))

【讨论】:

  • 感谢马特的帮助......这解决了我的问题......,☺
  • @mak 如果有用,请考虑accepting as an answer
猜你喜欢
  • 2014-02-15
  • 1970-01-01
  • 1970-01-01
  • 2019-02-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-15
  • 2016-10-22
相关资源
最近更新 更多