Functions and Statistics

The video below provides info about functions and statistics in R. If you prefer to read, then continue on my friend!

Functions are helpful as they have the ability to provide a lot of information. For example, when you use the function t.test(), it provides a description, the t statistic, the degrees of freedom, a p value, a confidence interval and much more. However, in some analyses, we only wanted one statistic that the function provided. Additionally, we may not know what the function calls the p value for example. We also might have needed to do 100 t tests, so it is valuable to do this efficiently instead of manually doing 100 t test. So we need a way to find out what the function calls each statistic and how to only recall that specific one. Later we will discuss how to use loops to more effectively do multiple actions more efficiently, however, we will focus on finding the names and call specific statistics. This is used by means of the symbol $ and the function names().

The names() Function

The names() function can be used to discover what objects a function produces. Below we provide the output in R of the names function being applied on a t.test between two different data sets.

Figure 1
Figure 1

Notice that we had the function of interest be applied on actual data. The names() function will not work unless it is being applied on a function that is processes data. Simply typing

names(t.test)

will not work. Also notice that it calls the t statistic simply “statistic”. We can now realize that the objects a function has may have obscure names then what we might call them in the vernacular.

Example I

What are the objects that the ks.test() function produces? Use this data here.

Answer I

The ks.test() function produces the following: statistic, p.value, alternative, method, and data.name. Below we provide the code and output in R.

mydata<-read.table('functions_and_statistics_data1.csv', sep=',') #loading in the data
mydata<-as.matrix(mydata) #converting the data into a matrix

names(ks.test(x,y))
Figure 2
Figure 2

 

The $ Symbol

Now that we know how to discover what the names of the objects are for a function, we now need to be able to just recall that object. To do this, type in a function as you normally would, but add the $ symbol and the object of desire. Let us do an example.

Example II

What are the names of the objects for the shapiro.test() function? Recall only the W statistic. Use this data here but only the first column.

Answer II

The shapiro.test() function produces the following: statistic, p.value, method, and data.name. Below we provide the code and output in R.

mydata<-read.table('functions_and_statistics_data1.csv', sep=',') #loading in the data
mydata<-as.matrix(mydata) #converting the data into a matrix

names(shapiro.test(x))

shapiro.test(x)$statistic

 

Figure 3
Figure 3