对可选参数的数据框进行子集化的功能

时间:2018-07-27 08:53:08

标签: r

我有一个数据框,如下所示:

df1 <- data.frame(
   Country = c("France", "England", "India", "America", "England"),
   City = c("Paris", "London", "Mumbai", "Los Angeles", "London"),
   Order_No = c("1", "2", "3", "4", "5"),
   delivered = c("Yes", "no", "Yes", "No", "yes"),
  stringsAsFactors = FALSE
)

以及其他多个列(大约50个)

我想编写一个通用的函数,可以接受用户想要的尽可能多的参数,并仅返回那些特定列的子集。因此,从技术上讲,用户应该能够传递1列或30列以从函数中获取结果

利用我在网上可以找到的可选参数,我编写了以下代码,但遇到了问题。有人可以帮我从这里出去吗?

SubsetFunction <- function(inputdf, ...)
{
      params <- vector(...)
      subset.df <- subset(inputdf, select = params)
      return(subset.df)
}

这是我遇到的错误-

  vector(...)中的

错误:         向量:无法制作“国家/地区”模式的向量。

2 个答案:

答案 0 :(得分:1)

我们可以在此处使用missing函数来检查参数是否存在

select_cols <- function(df, cols) {
   if(missing(cols))
      df
   else
      df[cols]
}

select_cols(df1, c("Country", "City"))

#  Country        City
#1  France       Paris
#2 England      London
#3   India      Mumbai
#4 America Los Angeles
#5 England      London

select_cols(df1)

#   Country        City Order_No delivered
#1  France       Paris        1       Yes
#2 England      London        2        no
#3   India      Mumbai        3       Yes
#4 America Los Angeles        4        No
#5 England      London        5       yes

答案 1 :(得分:1)

使用vector(...)在这里造成了问题。必须将省略号转换为列表。因此,为了最终从三点参数中获得向量,应该使用看似笨拙的构造unlist(list(...))代替vector(...)

SubsetFunction <- function(inputdf, ...){
  params <- unlist(list(...))
  subset.df <- subset(inputdf, select=params)
  return(subset.df)
}

这允许使用任意数量的参数调用函数SubsetFunction()

> SubsetFunction(df1, "City")
#         City
#1       Paris
#2      London
#3      Mumbai
#4 Los Angeles
#5      London
> SubsetFunction (df1, "City", "delivered")
#         City delivered
#1       Paris       Yes
#2      London        no
#3      Mumbai       Yes
#4 Los Angeles        No
#5      London       yes