nostats
nostats

Reputation: 3

Extracting specific data from predefined R function

I am trying to figure out how I can extract a specific portion of output from a predefined R function. A simple exampled would be, if I would like to store the mean value calculated via the summary() function. I know that I could simply use the mean() function, but again, this is a simple example.

If I am running the summary() function on several datasets within a loop, I would like to store the calculated mean from each dataset (possibly in a new vector, say named 'means'), for later use. Here's a quick example of what I have tried:

>sum <- summary(data$Column1)
>sum
 Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
 0.0300  0.1500  0.2200  0.3471  0.4000  2.5000 
>names(sum)
[1] "Min."    "1st Qu." "Median"  "Mean"   
[5] "3rd Qu." "Max."   
>sum$Mean
Error in sum$Mean : $ operator is invalid for atomic vectors

Upvotes: 0

Views: 165

Answers (2)

ndoogan
ndoogan

Reputation: 1925

You can skip the step of storing the whole output of the function by subsetting the function directly

means<-vector()
means[1]<-summary(data$Column1)["Mean"]

Upvotes: 1

csgillespie
csgillespie

Reputation: 60522

Your variable sum is a named vector. To extract elements, use

sum["Mean"]

or

sum[4]

One point. Avoid using sum, since this is also the name of a standard function.

Upvotes: 2

Related Questions