强制mapply返回列表?

发布于 2024-12-24 21:22:47 字数 673 浏览 1 评论 0原文

假设我有一个创建数据框的函数。我想使用不同的输入值运行该函数,然后将结果一起绑定到一个大数据框中,如下所示:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

﹎☆浅夏丿初晴 2024-12-31 21:22:47

要获取 data.frames 列表作为返回值,请将 mapplySIMPLIFY 参数设置为 FALSE。 (它的默认值为 TRUE,它指示函数“尝试将结果减少为向量、矩阵或更高维数组”——正是您所经历的)。

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

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

To get a list of data.frames as the return value, set mapply's SIMPLIFY argument to 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).

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

identical(class(res), "list")
[1] TRUE
素衣风尘叹 2024-12-31 21:22:47

您也可以使用地图功能。它基本上就是将 SIMPLIFY 设置为 FALSE 的 mapply。

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

Alternative you can use the Map function. It is basically mapply with SIMPLIFY set to FALSE.

Map("CreateDataFrame", type=toupper(letters[1:5]), n=10, n.true=8:4)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文