Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: Access column name within function with geom_line

Tags:

r

ggplot2

I have the following list of plots generated with lapply. Within functions subset and aes_string I don't seem to have problems passing the object i (the column name):

require(ggplot2)

cols <- colnames(mtcars)
lapply(cols[2:length(cols)], 
       function(i) {
         ggplot(subset(mtcars, get(i)>0), aes_string(x=i)) +
           geom_histogram() # +
#            geom_vline(aes(xintercept=mean(get(i), na.rm=T)),
#                       color="red", linetype="dashed", size=1)

         }
       )

And yet if I uncomment geom_line I receive the following error

## Error in get(i) : object 'i' not found
like image 843
CptNemo Avatar asked May 31 '26 11:05

CptNemo


1 Answers

Unfortunately xintercept doesn't work in aes, so the object really doesn't exist in the environment of geom_vline.

You can use this as a quick fix:

cols <- colnames(mtcars)
lapply(cols[2:length(cols)], 
       function(i) { Mean = with(mtcars, mean(get(i), na.rm=T));
           ggplot(subset(mtcars, get(i)>0), aes_string(x=i)) +
               geom_histogram()  +
                       geom_vline(xintercept=Mean,
                                  color="red", linetype="dashed", size=1)

       }
)
like image 128
Señor O Avatar answered Jun 04 '26 17:06

Señor O