SSExamine
public class SSExamine<SSElement, FPT> : NSObject, SSExamineContainer, NSCopying, Codable where SSElement : Comparable, SSElement : Decodable, SSElement : Encodable, SSElement : Hashable, FPT : Decodable, FPT : Encodable, FPT : SSFloatingPoint
SSExamine
This class contains all the data that you want to evaluate. SSExamine expects data that corresponds to the Hashable
, Comparable
and Codable
protocols.
Which statistics are available depends on the type of data. For nominal data, for example, an average will not be meaningful and will therefore not be calculated.
If a certain statistical measure is not available, the result will be nil
. It is therefore important that you check all results for this.
SSExamine was primarily developed with Objective-C and had in particular the requirement to create frequency tables for the entered data and to update these tables whenever data was added or removed. Internally, the data is therefore stored in a kind of frequency table. If, for example, the element “A” occurs a 100 times in the data set to be evaluated, the element is not stored 100 times, but only once. At the same time, a reference to the frequency of thi element is saved.
If elements are added to an SSExamine instance, the order of “arrival” is also registered. This makes it possible to reconstruct the “original data” from an SSExamine instance.
Important
SSElement
= The Type of data to be processed.FPT
= The type of emitted statistics. Must conform to SSFloatingPoint
-
An object representing the content of the SSExamine instance (experimental). A placeholder to specify the type of stored data.
Declaration
Swift
public var rootObject: Any?
-
User defined tag
Declaration
Swift
public var tag: String?
-
Human readable description
Declaration
Swift
public var descriptionString: String?
-
Name of the table
Declaration
Swift
public var name: String?
-
Undocumented
Declaration
Swift
public var alpha: FPT { get set }
-
Indicates if there are changes
Declaration
Swift
public var hasChanges: Bool!
-
Defines the level of measurement
Declaration
Swift
public var levelOfMeasurement: SSLevelOfMeasurement!
-
If true, the instance contains numerical data
Declaration
Swift
public var isNumeric: Bool!
-
Returns the number of unique SSElements
Declaration
Swift
public var length: Int { get }
-
Returns true, if count == 0, i.e. there are no data
Declaration
Swift
public var isEmpty: Bool { get }
-
The total number of observations (= sum of all absolute frequencies)
Declaration
Swift
public var sampleSize: Int { get }
-
Returns a Dictionary
,cumulative frequency > Declaration
Swift
public var cumulativeRelativeFrequencies: Dictionary<SSElement, FPT> { get }
-
Returns a the hash for the instance.
Declaration
Swift
public override var hash: Int { get }
-
Overridden Two SSExamine objects are assumed to be equal, iff the arrays of all elements in unsorted order are equal.
Important
Properties like “name” or “tag” are not includedDeclaration
Swift
public override func isEqual(_ object: Any?) -> Bool
Parameters
object
The object to compare to
-
Returns all unique elements as a Dictionary <element<SSElement>:frequency<Int>>
Declaration
Swift
public var elements: Dictionary<SSElement, Int> { get }
-
Returns a dictionary containing one array for each element. This array contains the order in which the elements were appended.
Declaration
Swift
public var sequences: Dictionary<SSElement, Array<Int>> { get }
-
Undocumented
Declaration
Swift
public override init()
-
Initializes a SSExamine instance using a string or an array
Throws
SSSwiftyStatsError.missingData if object is not a string or an Array<SSElement>Declaration
Swift
public init(withObject object: Any, levelOfMeasurement lom: SSLevelOfMeasurement, name: String?, characterSet: CharacterSet?) throws
Parameters
object
The object used
name
The name of the instance.
characterSet
Set containing all characters to include by string analysis. If a type other than String is used, this parameter will be ignored. If a string is used to initialize the class and characterSet is nil, then all characters will be appended.
lom
Level of Measurement
-
Returns: New table by analyzing string. Taking characterSet into account, when set
Declaration
Swift
public init(withArray array: Array<SSElement>, name: String?, characterSet: CharacterSet?)
Parameters
array
The array containing the elements
characterSet
Set containing all characters to include by string analysis. If a type other than String is used, this parameter will be ignored. If a string is used to initialize the class and characterSet is nil, then all characters will be appended.
-
Loads the content of a file interpreting the elements separated by
separator
as values using the specified encoding. Data are assumed to be numeric.The property
name
will be set to filename.Throws
SSSwiftyStatsError if the file doesn’t exist or can’t be accessed.Important
It is assumed that the elements are numeric.Declaration
Swift
public class func examine(fromFile path: String, separator: String, elementsEnclosedBy: String? = nil, stringEncoding: String.Encoding = String.Encoding.utf8, _ parser: (String?) -> SSElement?) throws -> SSExamine<SSElement, FPT>?
Parameters
path
The path to the file (e.g. ~/data/data.dat)
separator
The separator used in the file
stringEncoding
The encoding to use. Default: .utf8
elementsEnclosedBy
A string that encloses each element.
-
Imitializes a new Instance from a json file created by
exportJSONString(fileName:, atomically:, overwrite:, stringEncoding:)
Throws
if the file doesn’t exist or can’t be accessed or a the json file is invalidDeclaration
Swift
public class func examine(fromJSONFile path: String, stringEncoding: String.Encoding = String.Encoding.utf8) throws -> SSExamine<SSElement, FPT>?
Parameters
path
The path to the file (e.g. ~/data/data.dat)
stringEncoding
The encoding to use.
-
Exports the object as JSON to the given path using the specified encoding.
Throws
SSSwiftyStatsError if the file could not be writtenDeclaration
Swift
public func exportJSONString(fileName path: String, atomically: Bool = true, overwrite: Bool, stringEncoding: String.Encoding = String.Encoding.utf8) throws -> Bool
Parameters
path
Path to the file
atomically
If true, the object will be written to a temporary file first. This file will be renamed upon completion.
overwrite
If true, an existing file will be overwritten.
stringEncoding
String encoding
-
TODO: enclose elements in “” Saves the object to the given path using the specified encoding.
Throws
SSSwiftyStatsError if the file could not be writtenDeclaration
Swift
public func saveTo(fileName path: String, atomically: Bool = true, overwrite: Bool, separator: String = ",", encloseElementsBy: String? = nil, asRow: Bool = true, stringEncoding: String.Encoding = String.Encoding.utf8) throws -> Bool
Parameters
path
Path to the file
atomically
If true, the object will be written to a temporary file first. This file will be renamed upon completion.
overwrite
If true, an existing file will be overwritten.
separator
Separator to use.
stringEncoding
String encoding
encloseElementsBy
Defaulf = nil
-
Returns a SSExamine instance initialized using the string provided. Level of measurement will be set to .nominal.
Declaration
Swift
public class func examineWithString(_ string: String, name: String?, characterSet: CharacterSet?) -> SSExamine<String, FPT>?
Parameters
string
String
characterSet
If characterSet is not nil, only characters contained in the set will be appended
-
Declaration
Swift
public func encode(to encoder: Encoder) throws
-
Declaration
Swift
required public init(from decoder: Decoder) throws
-
Undocumented
Declaration
Swift
public func copy(with zone: NSZone? = nil) -> Any
-
Returns true, if the table contains the item
Declaration
Swift
public func contains(_ element: SSElement) -> Bool
Parameters
item
Item to search
-
Returns the relative Frequency of item
Declaration
Swift
public func rFrequency(_ element: SSElement) -> FPT
Parameters
element
Item
-
Returns the absolute frequency of item
Declaration
Swift
public func frequency(_ element: SSElement) -> Int
Parameters
element
Item
-
Appends
- and updates frequencies
Declaration
Swift
public func append(_ element: SSElement)
Parameters
element
Item
-
Appends n elements
Declaration
Swift
public func append(repeating n: Int, element: SSElement)
Parameters
n
Count of elements to append
elements
Item to append
-
Appends elements from an array
Declaration
Swift
public func append(contentOf array: Array<SSElement>)
Parameters
array
Array containing elements to add
-
Appends the characters of the given string. Only characters contained in the character set are appended.
Throws
SSSwiftyStatsError ifof the receiver is not of type String Declaration
Swift
public func append(text: String, characterSet: CharacterSet?) throws
Parameters
text
The text
characterSet
A CharacterSet containing the characters to include. If nil, all characters of text will be appended.
-
Removes item from the table.
Declaration
Swift
public func remove(_ element: SSElement, allOccurences all: Bool = false)
Parameters
item
Item
allOccurences
If false, only the first item found will be removed. Default: false
-
Removes all elements leaving an empty object
Declaration
Swift
public func removeAll()
-
Saves the table to filePath using NSKeyedArchiver.
Throws
SSSwiftyStatsError.posixError (file can'r be removed), SSSwiftyStatsError.directoryDoesNotExist, SSSwiftyStatsError.fileNotReadableDeclaration
Swift
public func archiveTo(filePath path: String!, overwrite: Bool!) throws -> Bool
Parameters
path
The full qualified filename.
overwrite
If yes an existing file will be overwritten.
-
Initializes a new table from an archive saved by archiveTo(filePath path:overwrite:).
Throws
SSSwiftyStatError.fileNotReadableDeclaration
Swift
public class func unarchiveFrom(filePath path: String!) throws -> SSExamine<SSElement, Double>?
Parameters
path
The full qualified filename.
-
Returns the Sn statistics according to Christophe Croux and Peter Rousseeuw
Sn is a unbiased estimate of the standard deviation of Gaussian distributed data. The returned result is bias corrected for small samples.
Note
Original Fortran code written by Christophe Croux and Peter Rousseeuw This Swift version was ported from a C version by Martin Maechler, maechler@R-project.org
Declaration
Swift
public var Sn: FPT? { get }
-
Returns the Qn statisticx by Rousseeuw, P.J. and Croux, C. (1993)
Declaration
Swift
public var Qn: FPT? { get }
-
Sum over all squared elements. Returns Double.nan iff data are non-numeric.
Declaration
Swift
public var squareTotal: FPT { get }
-
Sum of all elements raised to power p
Declaration
Swift
public func poweredTotal(power p: FPT) -> FPT?
Parameters
p
Power
-
Total of all elements. Returns Double.nan iff data are non-numeric.
Declaration
Swift
public var total: FPT? { get }
-
Returns the sum of all inverted elements
Declaration
Swift
public var inverseTotal: FPT? { get }
-
Returns the total of squares about the mean. If a user defined
value
is supplied, that value will be used.Note
If
value
is nil,self.arithmeticMean
will be used.Declaration
Swift
public func tss(value: FPT? = nil) -> FPT?
Parameters
value
value
-
Arithemtic mean. Will be Double.nan for non-numeric data.
Declaration
Swift
public var arithmeticMean: FPT? { get }
-
The mode. Can contain more than one item. Can be nil for empty tables.
Declaration
Swift
public var mode: Array<SSElement>? { get }
-
An arrayof the most common item(s). Same as mode. nil for empty tables.
Declaration
Swift
public var commonest: Array<SSElement>? { get }
-
An array containing scarcest element(s). nil for empty tables.
Declaration
Swift
public var scarcest: Array<SSElement>? { get }
-
Returns the q-quantile.
Throws
SSSwiftyStatsError.invalidArgument if data are non-numeric and/or if 0 < q >=1Declaration
Swift
public func quantile(q: FPT) throws -> FPT?
-
Returns a SSQuartile struct or nil for empty or non-numeric tables.
Declaration
Swift
public var quartile: SSQuartile<FPT>? { get }
-
Returns the geometric mean.
Declaration
Swift
public var geometricMean: FPT? { get }
-
Harmonic mean. Can be nil for non-numeric data.
Declaration
Swift
public var harmonicMean: FPT? { get }
-
Returns the contraharmonic mean (== (mean of squared elements) / (arithmetic mean))
Declaration
Swift
public var contraHarmonicMean: FPT? { get }
-
Returns the powered mean of order n
Declaration
Swift
public func poweredMean(order: FPT) -> FPT?
Parameters
n
The order of the powered mean
Return Value
The powered mean, nil if the receiver contains non-numerical data.
-
Returns the trimmed mean of all elements after dropping a fraction of alpha of the smallest and largest elements.
Throws
Throws an error if alpha <= 0 or alpha >= 0.5Declaration
Swift
public func trimmedMean(alpha: FPT) throws -> FPT?
Parameters
alpha
Fraction to drop
-
Returns the mean after replacing a given fraction (alpha) at the high and low end with the most extreme remaining values.
Throws
Throws an error if alpha <= 0 or alpha >= 0.5Declaration
Swift
public func winsorizedMean(alpha: FPT) throws -> FPT?
Parameters
alpha
Fraction
-
Returns the Gastwirth estimator (https://www.r-bloggers.com/gastwirths-location-estimator/)
Declaration
Swift
public var gastwirth: FPT? { get }
-
The median. Can be nil for non-numeric data.
Declaration
Swift
public var median: FPT? { get }
-
Product of all elements. Will be Double.nan for non-numeric data.
Declaration
Swift
public var product: FPT? { get }
-
The log-Product. Will be Double.nan for non-numeric data or if there is at least one item lower than zero. Returns -inf if there is at least one item equals to zero.
Declaration
Swift
public var logProduct: FPT? { get }
-
The largest item. Can be nil for empty tables.
Declaration
Swift
public var maximum: SSElement? { get }
-
The smallest item. Can be nil for empty tables.
Declaration
Swift
public var minimum: SSElement? { get }
-
The difference between maximum and minimum. Can be nil for empty tables.
Declaration
Swift
public var range: FPT? { get }
-
Returns the quartile devation (interquartile range / 2.0)
Declaration
Swift
public var quartileDeviation: FPT? { get }
-
Returns the relative quartile distance
Declaration
Swift
public var relativeQuartileDistance: FPT? { get }
-
Returns the mid-range
Declaration
Swift
public var midRange: FPT? { get }
-
Returns the interquartile range
Declaration
Swift
public var interquartileRange: FPT? { get }
-
Returns the interquartile range between two quantiles
Throws
SSSwiftyStatsError.invalidArgument if upper.isZero || upper < 0.0 || upper >= 1.0 || lower.isZero || lower < 0.0 || lower >= 1.0 || upper < lowerDeclaration
Swift
public func interquantileRange(lowerQuantile lower: FPT, upperQuantile upper: FPT) throws -> FPT?
Parameters
lower
Lower quantile
upper
Upper quantile
-
Returns the sample variance.
Declaration
Swift
public func variance(type: SSVarianceType) -> FPT?
Parameters
type
Can be .sample and .unbiased
-
Returns the sample standard deviation.
Declaration
Swift
public func standardDeviation(type: SSStandardDeviationType) -> FPT?
Parameters
type
.biased or .unbiased
-
Returns the standard error of the sample
Declaration
Swift
public var standardError: FPT? { get }
-
Returns the entropy of the sample. Defined only for nominal or ordinal data
Declaration
Swift
public var entropy: FPT? { get }
-
Returns the relative entropy of the sample. Defined only for nominal or ordinal data
Declaration
Swift
public var relativeEntropy: FPT? { get }
-
Undocumented
Declaration
Swift
public var herfindahlIndex: FPT? { get }
-
Returns the Herfindahl measure
Declaration
Swift
public var conc: FPT? { get }
-
Returns the Gini coefficient
Declaration
Swift
public var gini: FPT? { get }
-
The normalized Gini measure
Declaration
Swift
public var giniNorm: FPT? { get }
-
The concentration ratio
Declaration
Swift
public func CR(_ g: Int) -> FPT?
-
Returns the alpha-confidence interval of the mean when the population variance is known
Declaration
Swift
public func normalCI(alpha a: FPT, populationSD sd: FPT) -> SSConfIntv<FPT>?
Parameters
a
Alpha
sd
Standard deviation of the population
-
Returns the alpha-confidence interval of the mean when the population variance is unknown
Declaration
Swift
public func studentTCI(alpha a: FPT) -> SSConfIntv<FPT>?
Parameters
a
Alpha
-
Returns the 0.95-confidence interval of the mean using Student’s T distribution.
Declaration
Swift
public var meanCI: SSConfIntv<FPT>? { get }
-
Returns the coefficient of variation. A shorctut for coefficientOfVariation:
Declaration
Swift
public var cv: FPT? { get }
-
Returns the coefficient of variation
Declaration
Swift
public var coefficientOfVariation: FPT? { get }
-
Returns the mean absolute difference
Declaration
Swift
public var meanDifference: FPT? { get }
-
Returns the median absolute deviation around the reference point given (
rp
). If you would like to know the median absoulute deviation from the median, you can do so by setting the reference point to the medianDeclaration
Swift
public func medianAbsoluteDeviation(center rp: FPT, scaleFactor c: FPT?) -> FPT?
Parameters
rp
Reference point
scaleFactor
Used for consistency reasons. If nil, the default value will be used. ### Note ### The scale factor is valid for normally distributed data only.
-
Returns the mean absolute deviation around the reference point given. If you would like to know the mean absoulute deviation from the median, you can do so by setting the reference point to the median
Declaration
Swift
public func meanAbsoluteDeviation(center rp: FPT) -> FPT?
Parameters
rp
Reference point
-
Returns the relative mean absolute difference
Declaration
Swift
public var meanRelativeDifference: FPT? { get }
-
Returns the semi-variance
Declaration
Swift
public func semiVariance(type: SSSemiVariance) -> FPT?
Parameters
type
SSSemiVariance.lower or SSSemiVariance.upper
-
Returns the r_th moment of the given type. If .central is specified, the r_th central moment of all elements with respect to their mean will be returned. If .origin is specified, the r_th moment about the origin will be returned. If .standardized is specified, the r_th standardized moment will be returned.
Declaration
Swift
public func moment(r: Int, type: SSMomentType) -> FPT?
Parameters
r
r
-
Returns the lag-n autocorrelation of the data.
Declaration
Swift
public func autocorrelation(n: Int = 1) throws -> Double?
Parameters
n
Lag (default = 1)
-
Returns the kurtosis excess
Declaration
Swift
public var kurtosisExcess: FPT? { get }
-
Returns the kurtosis.
Declaration
Swift
public var kurtosis: FPT? { get }
-
Returns the type of kurtosis.
Declaration
Swift
public var kurtosisType: SSKurtosisType? { get }
-
Returns the skewness.
Declaration
Swift
public var skewness: FPT? { get }
-
Returns the type of skewness
Declaration
Swift
public var skewnessType: SSSkewness? { get }
-
Returns true, if there are outliers.
Declaration
Swift
public func hasOutliers(testType: SSOutlierTest) -> Bool?
Parameters
testType
SSOutlierTest.grubbs or SSOutlierTest.esd (Rosner Test)
-
Returns an Array containing outliers if those exist. Uses the ESD statistics,
Declaration
Swift
public func outliers(alpha: FPT!, max: Int!, testType t: SSESDTestType) -> Array<SSElement>?
Parameters
alpha
Alpha
max
Maximum number of outliers to return
testType
SSOutlierTest.grubbs or SSOutlierTest.esd (Rosner Test)
-
Returns true, if the sammple seems to be drawn from a normally distributed population with mean = mean(sample) and sd = sd(sample)
Declaration
Swift
public var isGaussian: Bool? { get }
-
Undocumented
Declaration
Swift
public func testForDistribution(targetDistribution target: SSGoFTarget) throws -> SSKSTestResult<FPT>?
-
Returns the statistics needed to create a Box-Whisker Plot
Declaration
Swift
public var boxWhisker: SSBoxWhisker<SSElement, FPT>? { get }
Return Value
A SSBoxWhisker structure
-
Returns all elements as one string. Elements are delimited by del.
Declaration
Swift
public func elementsAsString(withDelimiter del: String?, asRow: Bool = true, encloseElementsBy: String? = nil) -> String?
Parameters
del
The delimiter. Can be nil or empty.
asRow
If true, the parameter
del
will be omitted. The Name of the instance will ve used as header for the rowencloseElementsBy
Default: nil.
-
Returns an array containing all elements.
Declaration
Swift
public func elementsAsArray(sortOrder: SSDataArraySortOrder) -> Array<SSElement>?
Parameters
sortOrder
The sort sortOrder.
Return Value
An array containing all elements sortOrdered as specified.
-
Returns an array containing all unique elements.
Declaration
Swift
public func uniqueElements(sortOrder: SSSortUniqeItems) -> Array<SSElement>?
Parameters
sortOrder
Sorting order
-
Returns the frequency table as an array, ordered as speciefied.
Declaration
Swift
public func frequencyTable(sortOrder: SSFrequencyTableSortOrder) -> Array<SSFrequencyTableItem<SSElement, FPT>>
Parameters
sortOrder
SSFrequencyTableSortsortOrder
-
Returns the cumulative frequency table
Declaration
Swift
public func cumulativeFrequencyTable(format: SSCumulativeFrequencyTableFormat) -> Array<SSCumulativeFrequencyTableItem<SSElement, FPT>>
Parameters
format
SSCumulativeFrequencyTableFormat
-
Empirical CDF of item
Declaration
Swift
public func eCDF(_ item: SSElement) -> FPT
Parameters
item
The item for which the cdf will be returned.
-
The smallest frequency. Can be nil for empty tables.
Declaration
Swift
public var smallestFrequency: Int? { get }
-
The largest frequency Can be nil for empty tables.
Declaration
Swift
public var largestFrequency: Int? { get }