0

I'm learning lapply, can someone please help me understand the code from the "function (x)", also what is the role of "$out"? Thank you

outs=lapply(names(qdata[,12:35]), function(x)
        hist(qdata[[x]], data=qdata, main="Histogram of Quality Trait",
             xlab=as.character(x), las=1.5)$out)
markus
  • 25,843
  • 5
  • 39
  • 58
Shahbaz
  • 37
  • 5
  • 1
    Some info on `(l)apply` can be found here: [Grouping functions (tapply, by, aggregate) and the *apply family](https://stackoverflow.com/questions/3505701/grouping-functions-tapply-by-aggregate-and-the-apply-family) – markus Dec 11 '20 at 23:00

1 Answers1

2

This simply produces a series of histograms. If we replace qdata with mtcars and make a couple of minor tweaks we get:

par(mfrow = c(3, 4))

lapply(names(mtcars),
       function(x) hist(mtcars[[x]],
                        main = "Histogram of Quality Trait",
                        xlab = as.character(x), las = 1.5))

enter image description here

What lapply is doing here is iterating through the column names and generating a histogram for each column.

There are a couple of oddities in the code you shared. $out is not a member of the object produced by hist, so as well as drawing the histograms, the code returns a list of NULL values. The $out is presumably just a way of preventing the list from spitting out pages of the contents of hist objects to the console. The outs variable is useless after this call.

Also, data is not a named parameter in hist so the original code produces warnings for me.

Another possibility is that this is a custom hist function rather than the base R version.

Allan Cameron
  • 147,086
  • 7
  • 49
  • 87
  • are we setting names(mtcars) as x in the code? – Shahbaz Dec 11 '20 at 23:08
  • 1
    @Shabaz not quite. The function takes one string at a time, so in the function we are setting x as `names(mtcars)[1]` in the first iteration, then `names(mtcars)[2]` and so on. It's really a way of passing the `names(mtcars)` vector one at a time rather than all together. – Allan Cameron Dec 11 '20 at 23:27