简体   繁体   English

强制mapply返回列表?

[英]Force mapply to return a list?

Suppose I have a function that creates data frames. 假设我有一个创建数据帧的函数。 I'd like to run that function with different input values, and then rbind the results together into one big data frame, as below: 我想用不同的输入值运行该函数,然后将结果整合到一个大数据框中,如下所示:

CreateDataFrame <- function(type="A", n=10, n.true=8) {
  data.frame(success=c(rep(TRUE, n.true), rep(FALSE, n - n.true)), type=type)
}
df <- do.call(rbind, lapply(toupper(letters[1:5]), CreateDataFrame))

My CreateDataFrame function takes three arguments. 我的CreateDataFrame函数有三个参数。 In the example above, the second and third arguments are held constant. 在上面的示例中,第二个和第三个参数保持不变。 I'd like to do the same as above, but have the second and third arguments change on each call. 我想像上面一样做,但每次调用都会改变第二个和第三个参数。 I think I have to use mapply, like this: 我想我必须使用mapply,像这样:

mapply("CreateDataFrame", type=toupper(letters[1:5]), n=10, n.true=8:4)

I'm having trouble because mapply isn't returning a list, which prevents me from running do.call(rbind, mapply(...)) . 我遇到麻烦,因为mapply没有返回列表,这阻止我运行do.call(rbind, mapply(...)) How can I end up with a single data frame, as I did in the example at the top? 我怎么能得到一个数据框,就像我在顶部的例子中所做的那样?

Looks like mapply is returning a matrix of lists. 看起来mapply正在返回一个列表矩阵。 I was expecting it to return a list of data frames. 我期待它返回一个数据框列表。 What should I do differently? 我该怎么办?

To get a list of data.frames as the return value, set mapply 's SIMPLIFY argument to FALSE . 要获取data.frames列表作为返回值,请将mapplySIMPLIFY参数设置为FALSE (Its default value is TRUE , which directs the function to "attempt to reduce the result to a vector, matrix or higher dimensional array" -- just what you experienced). (它的默认值为TRUE ,它将函数指向“尝试将结果减少为向量,矩阵或更高维数组” - 正如您所经历的那样)。

res <- mapply("CreateDataFrame", type=toupper(letters[1:5]), n=10, n.true=8:4, 
              SIMPLIFY = FALSE)

identical(class(res), "list")
[1] TRUE

Alternative you can use the Map function. 您可以选择使用Map功能。 It is basically mapply with SIMPLIFY set to FALSE. 它基本上与SIMPLIFY设置为FALSE。

Map("CreateDataFrame", type=toupper(letters[1:5]), n=10, n.true=8:4)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM