我正在使用lapply来加速数据探索。我要一次对所有数字变量进行箱形图绘制,并希望将变量名称传递到绘图中。
我试图定义名称并通过它。
library(ggplot2)
library(mass)
data(Boston)
num_vars = which(sapply(Boston, is.numeric))
ggBox <-function(index) {
X <- index
X_name <- names(index)
ggplot(Boston,aes("X",X)) + geom_boxplot() + ggtitle(X_name)
}
lapply(Boston[names(num_vars)],FUN=ggBox)
我对此尝试了不同的变体,它只是传递X或数字值,而没有名称。
答案 0 :(得分:0)
lapply()
只能将对象值传递给函数,并且不能包含其名称。
lapply(iris, FUN = names)
$Sepal.Length $Sepal.Width $Petal.Length
NULL NULL NULL
$Petal.Width $Species
NULL NULL
当我将数据帧的每一列传递给names()
时,可以看到每个单元格都是 NULL 。如果要同时使用值和名称,则需要设计双变量函数。
我以iris
数据集为例
ggBox <- function(x, name) {
ggplot(iris, aes("X", x)) + geom_boxplot() + ggtitle(name)
}
df <- iris[1:4]
name <- names(iris)[1:4]
以下3种方法等效:
mapply(FUN = ggBox, df, name, SIMPLIFY = F)
Map(f = ggBox, df, name)
purrr::map2(df, name, ggBox)