R: Enter the name of the column inside the function with geom_line

I have the following list of graphs generated with lapply

. Inside functions subset

and aes_string

I have no problem passing object i

(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 get the following error

## Error in get(i) : object 'i' not found

      

+3


source to share


2 answers


Unfortunately, it xintercept

doesn't work in aes

, so the object doesn't really exist in the environment 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)

       }
)

      

+4


source


You can use the aes_string

same as for x

aesthetic



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

      

0


source







All Articles