0

如何创建一个接受未终止数量参数的函数

在一个真实世界的例子中,在了解了这些信息后,我想完成以下创建函数的操作:

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)
}

在此先感谢您的帮助!

4

1 回答 1

1

因此,根据我收集到的信息,您想要一个包含 x 个数据帧的列表,并找到每个数据帧中所有观察值和所有变量的最大值。为什么不执行以下操作:

# Create list with 10 dataframes
df_list <- list()
for (i in 1:10) {
  df_list[[i]] <- data.frame(matrix(rnorm(100), ncol = 10))
  colnames(df_list[[i]]) <- LETTERS[1:10]
}

# Find maximum value of all data.frames
sapply(df_list, FUN = max)

这将创建一个包含 10 个数据框的列表,每个数据框有 10 个观察值和 10 个变量。然后它遍历每个 data.frame 以获得每个数据的最大值。最后,返回一个具有最大值的向量。

于 2017-08-24T17:57:22.763 回答