R中的二和函数

R中的二和函数,r,function,R,Function,我试图创建一个函数,该函数将拾取列表中的两个数字,这两个数字的总和为目标数字 有人能告诉我为什么我的代码不起作用吗 谢谢大家! TwoSum <- function(num, target) { for (i in 1:length(num) - 1) { for (j in i+1:length(num)) { if (num[i] + num[j] == target) { print("the numbers are:") pr

我试图创建一个函数,该函数将拾取列表中的两个数字,这两个数字的总和为目标数字

有人能告诉我为什么我的代码不起作用吗

谢谢大家!

TwoSum <- function(num, target) {
  for (i in 1:length(num) - 1) {
    for (j in i+1:length(num)) {
      if (num[i] + num[j] == target) {
        print("the numbers are:")
        print(paste0(num[i], num[j]))
        a <- a - 1
      }
    }
  }
  if (a == 1) {
    print("No pairs")
  }  
} 

a <- 1
num <- c(1,2,3,4,5)
target <- 7

TwoSum(num,target)

TwoSum在第二行和第三行引入大括号

TwoSum <- function(num, target) {
  for (i in 1:(length(num) - 1)) {
    for (j in (i+1):length(num)) {
      if (num[i] + num[j] == target) {
        print("the numbers are:")
        print(paste0(num[i], num[j]))
        a <- a - 1
    }
  }

TwoSum在第二行和第三行引入大括号

TwoSum <- function(num, target) {
  for (i in 1:(length(num) - 1)) {
    for (j in (i+1):length(num)) {
      if (num[i] + num[j] == target) {
        print("the numbers are:")
        print(paste0(num[i], num[j]))
        a <- a - 1
    }
  }

TwoSum您不应该为此使用循环。改用
combn

combs <- combn(num, 2)
combs[,colSums(combs) == target]
#     [,1] [,2]
#[1,]    2    3
#[2,]    5    4

combs您不应该为此使用循环。改用
combn

combs <- combn(num, 2)
combs[,colSums(combs) == target]
#     [,1] [,2]
#[1,]    2    3
#[2,]    5    4

combs感谢您的回复。。。我仍然在if(num[I]+num[j]==target){:参数的长度为零…感谢您的回复…我仍然在if(num[I]+num[j]==target){:参数的长度为零。。。