强制mapply返回列表?
假设我有一个创建数据框的函数。我想使用不同的输入值运行该函数,然后将结果一起绑定到一个大数据框中,如下所示:
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))
我的 CreateDataFrame 函数采用三个参数。在上面的示例中,第二个和第三个参数保持不变。我想做与上面相同的事情,但在每次调用时更改第二个和第三个参数。我想我必须使用mapply,如下所示:
mapply("CreateDataFrame", type=toupper(letters[1:5]), n=10, n.true=8:4)
我遇到了麻烦,因为mapply没有返回列表,这阻止了我运行do.call(rbind, mapply(...))
。我怎样才能得到一个单一的数据框,就像我在顶部的示例中所做的那样?
看起来 mapply 正在返回一个列表矩阵。我期望它返回数据帧列表。我应该采取什么不同的做法?
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. 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("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(...))
. 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. I was expecting it to return a list of data frames. What should I do differently?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
要获取 data.frames 列表作为返回值,请将
mapply
的SIMPLIFY
参数设置为FALSE
。 (它的默认值为 TRUE,它指示函数“尝试将结果减少为向量、矩阵或更高维数组”——正是您所经历的)。To get a list of data.frames as the return value, set
mapply
'sSIMPLIFY
argument toFALSE
. (Its default value isTRUE
, which directs the function to "attempt to reduce the result to a vector, matrix or higher dimensional array" -- just what you experienced).您也可以使用地图功能。它基本上就是将 SIMPLIFY 设置为 FALSE 的 mapply。
Alternative you can use the Map function. It is basically mapply with SIMPLIFY set to FALSE.