如何创建一个接受未终止数量参数的函数
在一个真实世界的例子中,在了解了这些信息后,我想完成以下创建函数的操作:
list.max <- function(list, ... )
其中 ... 表示列表中 data.frames 中的不同列。
该函数将逐行比较列中的元素,并返回一个具有最大值的向量。
为了帮助这个过程,我已经做了一些工作。这是我能得到的最接近的:
#function to return the maximum value from each line, between all the columns listed
#@Arg List: A list of data.frames which contain the columns
#@Arg col.name1 ... col.nameN: Character variable containing the names from the columns to compare
#Pre: The list must exist and the data.frames must contain the same columns
#Pos: The function will return a vector with their first element
# being the maximum value, between the columns listed, from the first
# data.frame from the list. The second element, being the maximum
# value between the columns listed, from the second data.frame from
# the list. The analogy continues until the N element
list.max <- function(list, col.name1, col.name2, ... , col.nameN){
#creates the first data.frame with the correct amount of rows
data.frame = data.frame(list.exapply(list, max, col.name1))
#loop intill the end
data.frame[1] = list.exapply(list, max, col.name1)
data.frame[2] = list.exapply(list, max, col.name2)
...
data.frame[N] = list.exapply(list, max, col.nameN)
#transpose the data.frame, so it can be compared in the max function, as he is casted to a matrix class
t(data.frame)
#creates the vector so it can storage the max value between the columns (which are now the lines)
vet = vector()
#storage the solution
for( i in 1:nrow(data.frame)) {vet[i] = max(data.frame[i,])}
#return the solution
return (vet)
}
上面用到的辅助功能有这些:
df.exapply <- function(data.frame, func, col.name){
variavel <-func(data.frame[, col.name])
# print(variavel)
return (variavel)
}
list.exapply <- function(list, func, col.name){
vet = df.exapply(list[[1]], func, col.name)
# print(col.name)
for (i in 1:length(list)) { vet[i] = df.exapply(list[[i]],func, col.name)
}
return (vet)
}
在此先感谢您的帮助!