循环遍历R中的当前函数

时间:2013-04-17 07:49:43

标签: r function

我已经生成了以下函数,该函数根据输入值的范围执行操作:

foof <- function(height,age){

# we have a choice of two methods to use
# initially set both methods to false
SS = FALSE; # method 1
TT = FALSE; # method 2

# set range for values 
H_rng <- c(0.5,20) # height range
A_rng <- c(0,60) # age range


# check to see if all values lie within the ranges specified
if (isTRUE(all(height<H_rng[1]))){
  SS <- TRUE # use method 1
} else if(!(sum(age<A_rng[1])||sum(age>A_rng[2])) && !(sum(height<H_rng[1]))||sum(height>H_rng[2])){
  TT <- TRUE # use method 2
}


if (SS == TRUE){
  Vals <- SS+TT
}

if (TT == TRUE){
  Vals <- SS-TT
}

return(Vals)

}

其中用于特定计算的等式取决于输入数组的值。该函数基本上查看输入参数中的所有值,然后如果所有这些值都在指定的范围内,则使用显示的等式来计算答案。但是,我想知道如何改变它来查看输入变量中的每个单独的值,然后使用正确的等式。这很难用文字描述,所以我将展示一个例子:

height <- c(0,0,0,0,0,0,0,0)
height <- matrix(height,nrow = 2)

age <- c(18,9,22,3,4,6,7,32)
age <- matrix(age,nrow = 2)

f <- foof(height,age)

这很好,因为所有'height'都低于H_rng因此它使用方法1.

如果我改变这个

height <- c(0,0,0,0,0,0,2,0)
height <- matrix(height,nrow = 2)

age <- c(18,9,22,3,4,6,7,32)
age <- matrix(age,nrow = 2)

f <- foof(height,age)

该函数不会返回任何输出,这是由于高度上的所有值都不小于H_rng。

因此,我需要在函数末尾添加类似循环的内容,如果SS和TT都是假的,那么我们分别查看高度和年龄的每个条目并返回数组中的值。我试过这样做:

foof <- function(height,age){

# initially set both methods to false
SS = FALSE; # method 1
TT = FALSE; # method 2

# set range for values 
H_rng <- c(0.5,20) # height range
A_rng <- c(0,60) # age range


# check to see if all values lie within the ranges specified
if (isTRUE(all(height<H_rng[1]))){
  SS <- TRUE # use method 1
} else if(!(sum(age<A_rng[1])||sum(age>A_rng[2])) && !(sum(height<H_rng[1]))||sum(height>H_rng[2])){
  TT <- TRUE # use method 2
}

if (SS == TRUE){
  Vals <- SS+TT
}

if (TT == TRUE){
  Vals <- SS-TT
}

if (SS == FALSE && TT == FALSE){
  Vals <- 0
  for (i in 1:length(height)){
    Vals[i] <- foof(height[i],age[i])
  }     
}

return(Vals)

这会生成一个输出,但它与输入变量的尺寸不同,例如这里它是一个向量,而输入变量是一个矩阵。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

例如,您可以在最后一行之前添加此行:

.....
dim(Vals) <- dim(height)
return(Vals)