gpt4 book ai didi

r - lapply 中的匿名函数

转载 作者:行者123 更新时间:2023-12-04 12:04:34 45 4
gpt4 key购买 nike

我正在阅读 Wickham 的 Advanced R 书。此问题与解决第 12 章 - 泛函中的问题 5 有关。该练习要求我们:

Implement a version of lapply() that supplies FUN with both the name and value of each component.



现在,当我运行下面的代码时,我会得到一列的预期答案。
c(class(iris[1]),names(iris[1]))

输出是:
"data.frame"   "Sepal.Length"

基于上面的代码,这是我所做的:
lapply(iris,function(x){c(class(x),names(x))})

但是,我只能从 class(x) 获得输出而不是来自 names(x) .为什么会这样?

我也试过 paste()看看它是否有效。
lapply(iris,function(x){paste(class(x),names(x),sep = " ")})

我只有 class(x)在输出中。我没看到 names(x)被退回。

为什么会这样?另外,我该如何解决?

有人可以帮帮我吗?

最佳答案

您可以切换事物并让 lapply 遍历列名称的向量,而不是直接遍历数据框,

data(iris)

lapply(colnames(iris), function(x) c(class(iris[[x]]), x))

或在列的索引上,引用数据框。
lapply(1:ncol(iris), function(x) c(class(iris[[x]]), names(iris[x])))

注意单方括号和双方括号的使用。 iris[[n]]引用 n 的值列表中的第 th 个对象 iris (数据框只是一种特定类型的列表),剥离所有属性,生成类似 mean(iris[[1]]) 的内容可能的。 iris[n]引用 n th 对象本身,所有属性完好无损,制作类似 names(iris[1]) 的东西可能的。

关于r - lapply 中的匿名函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43908001/

45 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com