Reputation: 384
For a function, I need to keep variable names in a vector and I use a function to plot density graphs of my variables.
My problem is as follows in summary ;
var_names <- c("mpg","cyl","disp","hp","drat","wt","qsec","vs","am","gear","carb")
plotter <- function(x){
plot(density(x),
main = "",
xlab = "",
ylab = "")
title(var_names)
}
par(mfrow=c(4,3),mar=c(1,1,1,1))
apply(mtcars,2,plotter)
Couldn't imagine how I can match them.
Upvotes: 1
Views: 260
Reputation: 4427
var_names <- c("mpg","cyl","disp","hp","drat","wt","qsec","vs","am","gear","carb")
plotter <- function(x, var){
plot(density(x[[var]]),
main = var,
xlab = "",
ylab = "")
}
par(mfrow=c(4,3),mar=c(2.1,2.1,2.1,1))
for(vn in var_names) plotter(mtcars, vn)
for
loops are discouraged as they are slow. However in conjunction with plotting, which is slow in its own way or if the loop is only run for 11 times as in this example, for
loops are perfectly fine and beginner friendly.
If you really need an apply-family function of plotters to have only one argument, the following will do:
var_names <- c("mpg","cyl","disp","hp","drat","wt","qsec","vs","am","gear","carb")
plotter <- function(x){
plot(density(x[[1]]),
main = names(x),
xlab = "",
ylab = "")
}
par(mfrow=c(4,3),mar=c(2.1,2.1,2.1,1))
sapply(1:11,function(n) plotter(mtcars[n]))
Upvotes: 2
Reputation: 39613
I would suggest a tidyverse
approach with ggplot2
and the vector of names you have. You can format your data to longer and then filter the desired variables. Using facets and geom_density()
you can avoid issues with titles. Here the code:
library(tidyverse)
#Vector
var_names <- c("mpg","cyl","disp","hp","drat","wt","qsec","vs","am","gear","carb")
#Data
mtcars %>% pivot_longer(cols = everything()) %>%
filter(name %in% var_names) %>%
ggplot(aes(x=value))+
geom_density()+
facet_wrap(.~name,scales = 'free')+
theme_bw()
Output:
Upvotes: 2