使用函数和 lapply 制作正确标记的直方图
Using functions and lapply to make properly labelled histograms
我对使用函数和 lapply 制作正确标记的直方图很感兴趣。
但是当我尝试使用函数和 lapply 创建显示数据分布的直方图时,xlab 没有给出感兴趣变量的文本。相反,它使用感兴趣的变量的第一个值。我该如何解决这个问题?
我使用的代码如下:
# loads ggplot2 package
if(!require(ggplot2)){install.packages("ggplot2")} # ---- NOTE: relates to mlm analyses
# creates function_dataset_diamonds_DV_histogram
function_dataset_diamonds_DV_histogram <-
function(
DV_use
)
{
ggplot(diamonds, aes(x=as.numeric(DV_use))) +
geom_histogram(aes(y=..density..), alpha=0.5,
position="identity", binwidth = nclass.Sturges(DV_use)) +
geom_density(alpha=.2) +
theme(legend.position="right") +
xlab(DV_use)
}
# tests function
function_dataset_diamonds_DV_histogram(diamonds$carat)
# applies function
lapply((diamonds[c(1,8:10)]), function_dataset_diamonds_DV_histogram)
您正在将数据向量传递给 xlab,因此它只是将其截断为第一个值。你想传递一个字符串。
修改您的函数以获取标签值,然后使用 mapply
function_dataset_diamonds_DV_histogram <- function(DV_use, xLabel){
ggplot(diamonds, aes(x=as.numeric(DV_use))) +
geom_histogram(aes(y=..density..), alpha=0.5,
position="identity", binwidth = nclass.Sturges(DV_use)) +
geom_density(alpha=.2) +
theme(legend.position="right") +
xlab(xLabel)
}
mapply(function_dataset_diamonds_DV_histogram, diamonds[c(1,8:10)], names(diamonds[c(1,8:10)]), SIMPLIFY = FALSE)
我对使用函数和 lapply 制作正确标记的直方图很感兴趣。
但是当我尝试使用函数和 lapply 创建显示数据分布的直方图时,xlab 没有给出感兴趣变量的文本。相反,它使用感兴趣的变量的第一个值。我该如何解决这个问题?
我使用的代码如下:
# loads ggplot2 package
if(!require(ggplot2)){install.packages("ggplot2")} # ---- NOTE: relates to mlm analyses
# creates function_dataset_diamonds_DV_histogram
function_dataset_diamonds_DV_histogram <-
function(
DV_use
)
{
ggplot(diamonds, aes(x=as.numeric(DV_use))) +
geom_histogram(aes(y=..density..), alpha=0.5,
position="identity", binwidth = nclass.Sturges(DV_use)) +
geom_density(alpha=.2) +
theme(legend.position="right") +
xlab(DV_use)
}
# tests function
function_dataset_diamonds_DV_histogram(diamonds$carat)
# applies function
lapply((diamonds[c(1,8:10)]), function_dataset_diamonds_DV_histogram)
您正在将数据向量传递给 xlab,因此它只是将其截断为第一个值。你想传递一个字符串。
修改您的函数以获取标签值,然后使用 mapply
function_dataset_diamonds_DV_histogram <- function(DV_use, xLabel){
ggplot(diamonds, aes(x=as.numeric(DV_use))) +
geom_histogram(aes(y=..density..), alpha=0.5,
position="identity", binwidth = nclass.Sturges(DV_use)) +
geom_density(alpha=.2) +
theme(legend.position="right") +
xlab(xLabel)
}
mapply(function_dataset_diamonds_DV_histogram, diamonds[c(1,8:10)], names(diamonds[c(1,8:10)]), SIMPLIFY = FALSE)