cossim: Calculate the cosine similarity between two vectors...

View source: R/cossim.R

cossimR Documentation

Calculate the cosine similarity between two vectors (matrices)

Description

Calculate the cosine similarity between two vectors (matrices)

Usage

cossim(x, y, na.rm = TRUE)

Arguments

x

An integer or numeric vector or matrix

y

An integer or numeric vector or matrix

na.rm

Logical, whether NA should be removed

Details

If given as vectors, x and y must be of the same length. If given as matrices, both must have the same number of rows. If given as a pair of matrix and vector, the length of the vector must match the row number of the matrix. Otherwise the function aborts and prints error message.

If parameters are given as matrices, the function calculates the cossine similarity between all pair of columns of both matrices.

If na.rm is set FALSE, any NA in the input vectors will cause the result to be NA, or NaN if all values turn out to be NA.

Value

Numeric vector or matrix, the cossine similarity between the inputs

Note

Currently, na.rm is only considered when both inputs are vectors

Author(s)

Jitao David Zhang <jitao_david.zhang@roche.com>

References

http://en.wikipedia.org/wiki/Cosine_similarity

See Also

cor, cosdist

Examples

testVal1 <- rnorm(10)
testVal2 <- rnorm(10)
testVal3 <- c(rnorm(9), NA)

cossim(testVal1, testVal2)
cossim(testVal1, testVal3, na.rm=TRUE)
cossim(testVal1, testVal3, na.rm=FALSE)

cosdist(testVal1, testVal2)
cosdist(testVal1, testVal3, na.rm=TRUE)
cosdist(testVal1, testVal3, na.rm=FALSE)
## test matrix
testMat1 <- matrix(rnorm(1000), nrow=10)
testMat2 <- matrix(rnorm(1000), nrow=10)
system.time(testMatCos <- cossim(testMat1, testMat2))

testMatVec <- cossim(testMat1, testMat2[,1L])
testVecMat <- cossim(testMat1[,1L], testMat2)


bedapub/ribiosMath documentation built on Jan. 29, 2023, 1:48 p.m.