【问题标题】:Creating a variable number of arguments, function创建可变数量的参数,函数
【发布时间】:2018-02-02 15:24:07
【问题描述】:

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

在一个真实世界的例子中,在了解了这些信息后,我想通过以下方式创建函数:

list.max

其中 ... 表示来自 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)
}

提前感谢您的帮助!

【问题讨论】:

  • 你为什么不列出 2 个列表? 1 用于 data.frames 和 1 用于列,第二个列表也可以只是一个数组
  • 对不起,但是,接下来呢?我不明白这样做的功能。另外,当您说列列表时,您是指列名还是列本身?因为,如果您谈论的是列本身,如果我已经在第一个列表中包含此信息,为什么会有好处?

标签: r list function parameter-passing multiple-arguments


【解决方案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 以获得每个数据的最大值。最后返回一个具有最大值的向量。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-19
    • 1970-01-01
    相关资源
    最近更新 更多