This is the code in R and I\'m having trouble understanding the role of function(x)
and qdata[[x]]
in this line of code. Can someone elaborate me this
We don't have the data object named qdata
so we cannot really be sure what will happen with this code. It appears that the author of this code is trying to pass the values of components named outs
from function calls to hist
. If qdata
is an ordinary dataframe, then I suspect that this code will fail in that goal, because the hist
function does not have an out
component. (Look at the output of ?hist
. When I run this with a simple dataframe, I do get histogram plots that appear in my interactive plotting device but I get NULL
values for the outs
components. Furthermore the 12 warnings are caused by the lack of a data
parameter to hte hist function.
qdata <- data.frame(a=rnorm(10), b=rnorm(10))
outs=lapply(names(qdata), function(x)
hist(qdata[[x]],data=qdata,main="Histogram of Quality Trait",
xlab=as.character(x),las=1.5)$out)
#There were 12 warnings (use warnings() to see them)
> str(outs)
List of 2
$ : NULL
$ : NULL
So I think we need to be concerned about the level of R knowledge of the author of this code. It's possible I'm wrong about this presumption. The hist
function is generic and it is possible that some unreferenced package has a function designed to handle a data object and retrun an outs value when delivered a vector having a particular class. In a typical starting situation with only the base packages loaded however, there are only three hist.* functions:
methods(hist)
#[1] hist.Date* hist.default hist.POSIXt*
#see '?methods' for accessing help and source code
As far as the questions about the role of function
and [[x]]
: the keyword function
returns a language object that can receive parameter values and then do operations and finally return results. In this case the names
get passed to the anonymous function and become, each in turn, the local name, x
and the that value is used by the '[['
-function to look-up the column in what I am presuming is the ‘qdata’-dataframe.
This code generate a series of histograms, one for each of columns 12 to 35 of dataframe qdata. The lapply function iterates over the columns. At each iteraction, the name of the current column is passed as argument "x" to the anonymous function defined by "function(x)". The body of the function is a call to the hist() function, which creates the histogram. qdata[[x]] (where x is the name of a column) extracts the data from that column. I am actually confused by "data=qdata".