Extract normalised Eigenvectors in R - r

I have got the following code:
test <- ca.jo(x, type='trace', ecdet='const', K=2)
When I am writing summary(test) there occurs:
Eigenvectors, normalised to first column:
(These are the cointegration relations)
gld.l2 gdx.l2
gld.l2 1.000000 1.0000000
gdx.l2 -1.488325 -0.1993057
How can I call these normalized Eigenvectors?
When I am writing
slot(test, "Vorg")
I only get the following data
gld.l2 gdx.l2
gld.l2 -0.01346063 -0.012380092
gdx.l2 0.02003378 0.002467422
but I want to call the normalized ones.

data(denmark)
sjd <- denmark[, c("LRM", "LRY", "IBO", "IDE")]
sjd.vecm <- ca.jo(sjd, ecdet = "const", type="eigen", K=2, spec="longrun",
season=4)
sm <- summary(sjd.vecm)
sm#V
LRM.l2 LRY.l2 IBO.l2 IDE.l2 constant
LRM.l2 1.000000 1.0000000 1.0000000 1.000000 1.0000000
LRY.l2 -1.032949 -1.3681031 -3.2266580 -1.883625 -0.6336946
IBO.l2 5.206919 0.2429825 0.5382847 24.399487 1.6965828
IDE.l2 -4.215879 6.8411103 -5.6473903 -14.298037 -1.8951589
constant -6.059932 -4.2708474 7.8963696 -2.263224 -8.0330127
You might want to check str(sm) for more.

Related

Looping regression over increasing sample sizes in R

I am trying to store the coefficients & SEs of a linear regression in R. The regression starts with a sample size of 10 and needs to add 1 for each loop up to 1000. I have generated random variables (using rnorm), created variables to store the values in and can get the code to store the first regression, but it stops after 1 loop (sample size 10). What am I missing in my code here? Thank you for your help.
matrix_coef <-NULL
df <- data.frame(yi, x1, x2)
for (i in 10:1000) {
lm(df)
matrix_coef <- summary(lm(df))
b0[i]<- coef(matrix_coef)[1:1, 1:1]
bx1[i] <- coef(matrix_coef)[2:2, 1:1 ]
bx2[i] <- coef(matrix_coef)[3:3, 1:1]
sd0[i] <- coef(matrix_coef)[1:1, 2:2]
sdx1[i] <- coef(matrix_coef)[2:2, 2:2]
sdx2[i] <- coef(matrix_coef)[3:3, 2:2]
}
You've got a few issues:
Inside the loop, df doesn't change, you're always fitting lm to the full data. You need to use i to change the data that the model trains on. Something like lm(df[1:i, ]), perhaps (assuming your full data has 1000 rows and you want the iterations to fit the first 10, then 11, then 12, ... 1000 rows, rather than, say, resampling each time)
The line lm(df) by itself fits a model, but you don't do store the results and your next line summary(lm(df)) fits the exact same model again.
You initialize the wrong object. matrix_coef <- NULL essentially does nothing. The line matrix_coef <- summary(lm(df)) inside your loop will have no problem creating the matrix_coef object. (And we can save a bunch of typing by defining it as coef(summary(lm(df))) and not typing coef() on all the subsequent lines.) However, the objects that you index should be initialized, and preferably to the correct length.
1:1 is the same as 1. 2:2 is the same as 2, etc.
Addressing all of these gives us this:
set.seed(47)
n <- 15 ## small n for demonstration purposes
df <- data.frame(yi = rnorm(n), x1 = rnorm(n), x2 = rnorm(n))
b0 <- numeric(n)
bx1 <- numeric(n)
bx2 <- numeric(n)
sd0 <- numeric(n)
sdx1 <- numeric(n)
sdx2 <- numeric(n)
for (i in 10:n) {
matrix_coef <- coef(summary(lm(df[1:i, ])))
b0[i] <- matrix_coef[1, 1]
bx1[i] <- matrix_coef[2, 1]
bx2[i] <- matrix_coef[3, 1]
sd0[i] <- matrix_coef[1, 2]
sdx1[i] <- matrix_coef[2, 2]
sdx2[i] <- matrix_coef[3, 2]
}
b0
# [1] 0.00000000 0.00000000 0.00000000 0.00000000 0.00000000 0.00000000 0.00000000 0.00000000
# [9] 0.00000000 -0.17267676 -0.17490218 -0.08251370 -0.04048010 -0.04976162 -0.03881043
sdx2
# [1] 0.0000000 0.0000000 0.0000000 0.0000000 0.0000000 0.0000000 0.0000000 0.0000000 0.0000000 0.4888940
# [11] 0.4470402 0.4569932 0.4724890 0.4669553 0.4323498

extract rownames and column names from correlation matrix using aspecefic value

My aim is to eliminate duplicates from a dataset.
For that I wrote a program that calculates correlations.
I want to take the name of the variables that have a correlation higher than a specific value I determine.
Here's one of the results I got.
M926T709 M927T709_1 M927T709_2 M929T709
M926T709 1.0000000 0.9947082 0.9879702 0.8716944
M927T709_1 0.9947082 1.0000000 0.9955145 0.8785669
M927T709_2 0.9879702 0.9955145 1.0000000 0.8621052
M929T709 0.8716944 0.8785669 0.8621052 1.0000000
Let's say i want to obtain the name of variables that have percentage high than 95%
so i should obtain this result
M926T709 , M927T709_1 , M927T709_2
Edit : the answer given by Ronak Shah worked well , but i need to obtain the results as vector so i can use the names after
Note, that I shouldn't analyze orthogonal results because they always equal to 1.
Please tell me if you need any clarification, also tell me if you want to see my entire program.
Using rowSums and colSums you can count how many values are more than 0.95 in each row and column respectively and then return the names.
tmp <- mat > 0.95
diag(tmp) <- FALSE
names(Filter(function(x) x > 0, rowSums(tmp) > 0 | colSums(tmp) > 0))
#[1] "M926T709" "M927T709_1" "M927T709_2"
Sample data: the limit and the correlation matrix m (with an added negative correlation for demonstration purposes):
limit <- 0.95
m <- as.matrix( read.table(text = "
M926T709 M927T709_1 M927T709_2 M929T709
M926T709 1.0000000 -0.9947082 0.9879702 0.8716944
M927T709_1 -0.9947082 1.0000000 0.9955145 0.8785669
M927T709_2 0.9879702 0.9955145 1.0000000 0.8621052
M929T709 0.8716944 0.8785669 0.8621052 1.0000000"))
Create a subset of the desired matrix and extract the row/column names.
Target <- unique( # Remove any duplicates
unlist( # merge subvectors of the `dimnames` list into one
dimnames( # gives all names of rows and columns of the matrix below
# Create a subset of the matrix that ignores correlations < limit
m[rowSums(abs(m) * upper.tri(m) > limit) > 0, # Rows
colSums(abs(m) * upper.tri(m) > limit) > 0] # Columns
),
recursive = FALSE))
Target
#> [1] "M926T709" "M927T709_1" "M927T709_2"
Created on 2021-10-25 by the reprex package (v2.0.1)

Computing cosine.similarity in R gives different results compared to manual?

Here are my vectors:
lin_acc_mag_mean vel_ang_unc_mag_mean
<dbl> <dbl>
1 0.688 0.317
lin_acc_mag_mean vel_ang_unc_mag_mean
<dbl> <dbl>
1 2.94 0.324
or for simplicity:
a <- c(.688,.317)
b <- c(2.94, .324)
I want to compute tcR::cosine.similarity:
cosine.similarity(a,b, .do.norm = T) gives me 1.388816
If I will do it myself according to Wikipedia:
sum(c(.688,.317) * c(2.94, .324)) / (sqrt(sum(c(.688,.317) ^ 2)) * sqrt(sum(c(2.94, .324) ^ 2)))
And I get 0.948604 so what is different here?
Please advise. I suppose it is the normalization but will be happy for your help.
In the tcR package the cosine.similarity function contains the following:
function (.alpha, .beta, .do.norm = NA, .laplace = 0)
{
.alpha <- check.distribution(.alpha, .do.norm, .laplace)
.beta <- check.distribution(.beta, .do.norm, .laplace)
sum(.alpha * .beta)/(sum(.alpha^2) * sum(.beta^2))
}
The intervening check.distribution calculation returns a vector that sums to 1, but does not appear to be normalized.
I'd recommend using the cosine function in the lsa package, instead. This one produces the correct value. It also permits calculation of the cosine similarity for a whole matrix of vectors organized in columns. For example, cosine(cbind(a,b,b,a)) yields the following:
a b b a
a 1.000000 0.948604 0.948604 1.000000
b 0.948604 1.000000 1.000000 0.948604
b 0.948604 1.000000 1.000000 0.948604
a 1.000000 0.948604 0.948604 1.000000

cosine similarity(patient similarity metric) between 48k patients data with predictive variables

I have to calculate cosine similarity (patient similarity metric) in R between 48k patients data with some predictive variables. Here is the equation: PSM(P1,P2) = P1.P2/ ||P1|| ||P2||
where P1 and P2 are the predictor vectors corresponding to two different patients, where for example P1 index patient and P2 will be compared with index (P1) and finally pairwise patient similarity metric PSM(P1,P2) will be calculated.
This process will go on for all 48k patients.
I have added sample data-set for 300 patients in a .csv file. Please find the sample data-set here.https://1drv.ms/u/s!AhoddsPPvdj3hVTSbosv2KcPIx5a
First things first: You can find more rigorous treatments of cosine similarity at either of these posts:
Find cosine similarity between two arrays
Creating co-occurrence matrix
Now, you clearly have a mixture of data types in your input, at least
decimal
integer
categorical
I suspect that some of the integer values are Booleans or additional categoricals. Generally, it will be up to you to transform these into continuous numerical vectors if you want to use them as input into the similarity calculation. For example, what's the distance between admission types ELECTIVE and EMERGENCY? Is it a nominal or ordinal variable? I will only be modelling the columns that I trust to be numerical dependent variables.
Also, what have you done to ensure that some of your columns don't correlate with others? Using just a little awareness of data science and biomedical terminology, it seems likely that the following are all correlated:
diasbp_max, diasbp_min, meanbp_max, meanbp_min, sysbp_max and sysbp_min
I suggest going to a print shop and ordering a poster-size printout of psm_pairs.pdf. :-) Your eyes are better at detecting meaningful (but non-linear) dependencies between variable. Including multiple measurements of the same fundamental phenomenon may over-weight that phenomenon in your similarity calculation. Don't forget that you can derive variables like
diasbp_rage <- diasbp_max - diasbp_min
Now, I'm not especially good at linear algebra, so I'm importing a cosine similarity function form the lsa text analysis package. I'd love to see you write out the formula in your question as an R function. I would write it to compare one row to another, and use two nested apply loops to get all comparisons. Hopefully we'll get the same results!
After calculating the similarity, I try to find two different patients with the most dissimilar encounters.
Since you're working with a number of rows that's relatively large, you'll want to compare various algorithmic methodologies for efficiency. In addition, you could use SparkR/some other Hadoop solution on a cluster, or the parallel package on a single computer with multiple cores and lots of RAM. I have no idea whether the solution I provided is thread-safe.
Come to think of it, the transposition alone (as I implemented it) is likely to be computationally costly for a set of 1 million patient-encounters. Overall, (If I remember my computational complexity correctly) as the number of rows in your input increases, the performance could degrade exponentially.
library(lsa)
library(reshape2)
psm_sample <- read.csv("psm_sample.csv")
row.names(psm_sample) <-
make.names(paste0("patid.", as.character(psm_sample$subject_id)), unique = TRUE)
temp <- sapply(psm_sample, class)
temp <- cbind.data.frame(names(temp), as.character(temp))
names(temp) <- c("variable", "possible.type")
numeric.cols <- (temp$possible.type %in% c("factor", "integer") &
(!(grepl(
pattern = "_id$", x = temp$variable
))) &
(!(
grepl(pattern = "_code$", x = temp$variable)
)) &
(!(
grepl(pattern = "_type$", x = temp$variable)
))) | temp$possible.type == "numeric"
psm_numerics <- psm_sample[, numeric.cols]
row.names(psm_numerics) <- row.names(psm_sample)
psm_numerics$gender <- as.integer(psm_numerics$gender)
psm_scaled <- scale(psm_numerics)
pair.these.up <- psm_scaled
# checking for independence of variables
# if the following PDF pair plot is too big for your computer to open,
# try pair-plotting some random subset of columns
# keep.frac <- 0.5
# keep.flag <- runif(ncol(psm_scaled)) < keep.frac
# pair.these.up <- psm_scaled[, keep.flag]
# pdf device sizes are in inches
dev <-
pdf(
file = "psm_pairs.pdf",
width = 50,
height = 50,
paper = "special"
)
pairs(pair.these.up)
dev.off()
#transpose the dataframe to get the
#similarity between patients
cs <- lsa::cosine(t(psm_scaled))
# this is super inefficnet, because cs contains
# two identical triangular matrices
cs.melt <- melt(cs)
cs.melt <- as.data.frame(cs.melt)
names(cs.melt) <- c("enc.A", "enc.B", "similarity")
extract.pat <- function(enc.col) {
my.patients <-
sapply(enc.col, function(one.pat) {
temp <- (strsplit(as.character(one.pat), ".", fixed = TRUE))
return(temp[[1]][[2]])
})
return(my.patients)
}
cs.melt$pat.A <- extract.pat(cs.melt$enc.A)
cs.melt$pat.B <- extract.pat(cs.melt$enc.B)
same.pat <- cs.melt[cs.melt$pat.A == cs.melt$pat.B ,]
different.pat <- cs.melt[cs.melt$pat.A != cs.melt$pat.B ,]
most.dissimilar <-
different.pat[which.min(different.pat$similarity),]
dissimilar.pat.frame <- rbind(psm_numerics[rownames(psm_numerics) ==
as.character(most.dissimilar$enc.A) ,],
psm_numerics[rownames(psm_numerics) ==
as.character(most.dissimilar$enc.B) ,])
print(t(dissimilar.pat.frame))
which gives
patid.68.49 patid.9
gender 1.00000 2.00000
age 41.85000 41.79000
sysbp_min 72.00000 106.00000
sysbp_max 95.00000 217.00000
diasbp_min 42.00000 53.00000
diasbp_max 61.00000 107.00000
meanbp_min 52.00000 67.00000
meanbp_max 72.00000 132.00000
resprate_min 20.00000 14.00000
resprate_max 35.00000 19.00000
tempc_min 36.00000 35.50000
tempc_max 37.55555 37.88889
spo2_min 90.00000 95.00000
spo2_max 100.00000 100.00000
bicarbonate_min 22.00000 26.00000
bicarbonate_max 22.00000 30.00000
creatinine_min 2.50000 1.20000
creatinine_max 2.50000 1.40000
glucose_min 82.00000 129.00000
glucose_max 82.00000 178.00000
hematocrit_min 28.10000 37.40000
hematocrit_max 28.10000 45.20000
potassium_min 5.50000 2.80000
potassium_max 5.50000 3.00000
sodium_min 138.00000 136.00000
sodium_max 138.00000 140.00000
bun_min 28.00000 16.00000
bun_max 28.00000 17.00000
wbc_min 2.50000 7.50000
wbc_max 2.50000 13.70000
mingcs 15.00000 15.00000
gcsmotor 6.00000 5.00000
gcsverbal 5.00000 0.00000
gcseyes 4.00000 1.00000
endotrachflag 0.00000 1.00000
urineoutput 1674.00000 887.00000
vasopressor 0.00000 0.00000
vent 0.00000 1.00000
los_hospital 19.09310 4.88130
los_icu 3.53680 5.32310
sofa 3.00000 5.00000
saps 17.00000 18.00000
posthospmort30day 1.00000 0.00000
Usually I wouldn't add a second answer, but that might be the best solution here. Don't worry about voting on it.
Here's the same algorithm as in my first answer, applied to the iris data set. Each row contains four spatial measurements of the flowers form three different varieties of iris plants.
Below that you will find the iris analysis, written out as nested loops so you can see the equivalence. But that's not recommended for production with large data sets.
Please familiarize yourself with starting data and all of the intermediate dataframes:
The input iris data
psm_scaled (the spatial measurements, scaled to mean=0, SD=1)
cs (the matrix of pairwise similarities)
cs.melt (the pairwise similarities in long format)
At the end I have aggregated the mean similarities for all comparisons between one variety and another. You will see that comparisons between individuals of the same variety have mean similarities approaching 1, and comparisons between individuals of the same variety have mean similarities approaching negative 1.
library(lsa)
library(reshape2)
temp <- iris[, 1:4]
iris.names <- paste0(iris$Species, '.', rownames(iris))
psm_scaled <- scale(temp)
rownames(psm_scaled) <- iris.names
cs <- lsa::cosine(t(psm_scaled))
# this is super inefficient, because cs contains
# two identical triangular matrices
cs.melt <- melt(cs)
cs.melt <- as.data.frame(cs.melt)
names(cs.melt) <- c("enc.A", "enc.B", "similarity")
names(cs.melt) <- c("flower.A", "flower.B", "similarity")
class.A <-
strsplit(as.character(cs.melt$flower.A), '.', fixed = TRUE)
cs.melt$class.A <- sapply(class.A, function(one.split) {
return(one.split[1])
})
class.B <-
strsplit(as.character(cs.melt$flower.B), '.', fixed = TRUE)
cs.melt$class.B <- sapply(class.B, function(one.split) {
return(one.split[1])
})
cs.melt$comparison <-
paste0(cs.melt$class.A , '_vs_', cs.melt$class.B)
cs.agg <-
aggregate(cs.melt$similarity, by = list(cs.melt$comparison), mean)
print(cs.agg[order(cs.agg$x),])
which gives
# Group.1 x
# 3 setosa_vs_virginica -0.7945321
# 7 virginica_vs_setosa -0.7945321
# 2 setosa_vs_versicolor -0.4868352
# 4 versicolor_vs_setosa -0.4868352
# 6 versicolor_vs_virginica 0.3774612
# 8 virginica_vs_versicolor 0.3774612
# 5 versicolor_vs_versicolor 0.4134413
# 9 virginica_vs_virginica 0.7622797
# 1 setosa_vs_setosa 0.8698189
If you’re still not comfortable with performing lsa::cosine() on a scaled, numerical dataframe, we can certainly do explicit pairwise calculations.
The formula you gave for PSM, or cosine similarity of patients, is expressed in two formats at Wikipedia
Remembering that vectors A and B represent the ordered list of attributes for PatientA and PatientB, the PSM is the dot product of A and B, divided by (the scalar product of [the magnitude of A] and [the magnitude of B])
The terse way of saying that in R is
cosine.sim <- function(A, B) { A %*% B / sqrt(A %*% A * B %*% B) }
But we can rewrite that to look more similar to your post as
cosine.sim <- function(A, B) { A %*% B / (sqrt(A %*% A) * sqrt(B %*% B)) }
I guess you could even re-write that (the calculations of similarity between a single pair of individuals) as a bunch of nested loops, but in the case of a manageable amount of data, please don’t. R is highly optimized for operations on vectors and matrices. If you’re new to R, don’t second guess it. By the way, what happened to your millions of rows? This will certainly be less stressful now that your down to tens of thousands.
Anyway, let’s say that each individual only has two elements.
individual.1 <- c(1, 0)
individual.2 <- c(1, 1)
So you can think of individual.1 as a line that passes between the origin (0,0) and (0, 1) and individual.2 as a line that passes between the origin and (1, 1).
some.data <- rbind.data.frame(individual.1, individual.2)
names(some.data) <- c('element.i', 'element.j')
rownames(some.data) <- c('individual.1', 'individual.2')
plot(some.data, xlim = c(-0.5, 2), ylim = c(-0.5, 2))
text(
some.data,
rownames(some.data),
xlim = c(-0.5, 2),
ylim = c(-0.5, 2),
adj = c(0, 0)
)
segments(0, 0, x1 = some.data[1, 1], y1 = some.data[1, 2])
segments(0, 0, x1 = some.data[2, 1], y1 = some.data[2, 2])
So what’s the angle between vector individual.1 and vector individual.2? You guessed it, 0.785 radians, or 45 degrees.
cosine.sim <- function(A, B) { A %*% B / (sqrt(A %*% A) * sqrt(B %*% B)) }
cos.sim.result <- cosine.sim(individual.1, individual.2)
angle.radians <- acos(cos.sim.result)
angle.degrees <- angle.radians * 180 / pi
print(angle.degrees)
# [,1]
# [1,] 45
Now we can use the cosine.sim function I previously defined, in two nested loops, to explicitly calculate the pairwise similarities between each of the iris flowers. Remember, psm_scaled has already been defined as the scaled numerical values from the iris dataset.
cs.melt <- lapply(rownames(psm_scaled), function(name.A) {
inner.loop.result <-
lapply(rownames(psm_scaled), function(name.B) {
individual.A <- psm_scaled[rownames(psm_scaled) == name.A, ]
individual.B <- psm_scaled[rownames(psm_scaled) == name.B, ]
similarity <- cosine.sim(individual.A, individual.B)
return(list(name.A, name.B, similarity))
})
inner.loop.result <-
do.call(rbind.data.frame, inner.loop.result)
names(inner.loop.result) <-
c('flower.A', 'flower.B', 'similarity')
return(inner.loop.result)
})
cs.melt <- do.call(rbind.data.frame, cs.melt)
Now we repeat the calculation of cs.melt$class.A, cs.melt$class.B, and cs.melt$comparison as above, and calculate cs.agg.from.loops as the mean similarity between the various types of comparisons:
cs.agg.from.loops <-
aggregate(cs.agg.from.loops$similarity, by = list(cs.agg.from.loops $comparison), mean)
print(cs.agg.from.loops[order(cs.agg.from.loops$x),])
# Group.1 x
# 3 setosa_vs_virginica -0.7945321
# 7 virginica_vs_setosa -0.7945321
# 2 setosa_vs_versicolor -0.4868352
# 4 versicolor_vs_setosa -0.4868352
# 6 versicolor_vs_virginica 0.3774612
# 8 virginica_vs_versicolor 0.3774612
# 5 versicolor_vs_versicolor 0.4134413
# 9 virginica_vs_virginica 0.7622797
# 1 setosa_vs_setosa 0.8698189
Which, I believe is identical to the result we got with lsa::cosine.
So what I'm trying to say is... why wouldn't you use lsa::cosine?
Maybe you should be more concerned with
selection of variables, including removal of highly correlated variables
scaling/normalizing/standardizing the data
performance with a large input data set
identifying known similars and dissimilars for quality control
as previously addressed

Building markov chain in r

I have a text in a column and i would like to build a markov chain. I was wondering of there is a way to build markov chain for states A, B,C, D and generate a markov chain with that states. Any thoughts?
A<- c('A-B-C-D', 'A-B-C-A', 'A-B-A-B')
Since you mentioned that you know how to work with statetable.msm, here's a way to translate the data into a form it can handle:
dd <- c('A-B-C-D', 'A-B-C-A', 'A-B-A-B')
Split on dashes and arrange in columns:
d2 <- data.frame(do.call(cbind,strsplit(dd,"-")))
Arrange in a data frame, identified by sequence:
d3 <- tidyr::gather(d2)
Construct the transition matrix:
statetable.msm(value,key,data=d3)
If you want to compute the transition probability matrix (row stochastic) with MLE from the data, try this:
A <- c('A-B-C-D', 'A-B-C-A', 'A-B-A-B', 'D-B-C-A') # the data: by modifying your example data little bit
df <- as.data.frame(do.call(rbind, lapply(strsplit(A, split='-'), function(x) t(sapply(1:(length(x)-1), function(i) c(x[i], x[i+1]))))))
tr.mat <- table(df[,1], df[,2])
tr.mat <- tr.mat / rowSums(tr.mat) # make the matrix row-stochastic
tr.mat
# A B C D
# A 0.0000000 1.0000000 0.0000000 0.0000000 # P(A|A), P(B|A), P(C|A), P(D|A) with MLE from data
# B 0.2500000 0.0000000 0.7500000 0.0000000
# C 0.6666667 0.0000000 0.0000000 0.3333333
# D 0.0000000 1.0000000 0.0000000 0.0000000

Resources