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
Related
First some data. Make a dataframe for covariates and my outcome of interest for regression and one for explanatory variables.
What I am doing is stepping through the lm(outcome ~ mycovs + ith column of betas) and for this example, collecting the residuals.
set.seed(123) # for repeatability
mycovs = data.frame(outcome = rnorm(100,20,5),
race = rep(c("white","black","hispanic","other"),25),
income = rep(c("high","low"),50),
age = rnorm(100,30,3))
betas = data.frame(replicate(10000,rnorm(100,50,6)/100))
To do this for every variable in betas I wrote this code:
get_resids <- function(x){
mydata = cbind(mycovs,x)
cpg = names(mydata)[ncol(mydata)]
as.vector(resid(lm(formula(paste("outcome ~ as.factor(race) + as.factor(income) + age + ", cpg )),
data = mydata)))
}
head(get_resids(betas[1]))
[1] -1.8525090 -0.7299173 6.4941289 0.5357159 -0.1771154 7.7554550
Then I can use do.call(lapply()) to generate a matrix of these residuals for each of the 10,000 variables in my betas data frame as follows.
system.time(
myresids <- do.call(cbind, lapply(betas, get_resids))
)
user system elapsed
20.63 0.06 20.76
> dim(myresids)
[1] 100 10000
> myresids[1:5,1:10]
X1 X2 X3 X4 X5 X6 X7 X8 X9 X10
[1,] -1.8525090 -3.2651298 -3.54352587 -3.2962217 -2.95237520 -2.52995146 -3.0971490 -3.07625585 -2.8306409 -2.6454698
[2,] -0.7299173 -1.7982698 -2.54966496 -1.8009449 -1.60265484 -0.35825398 -1.6771846 -1.55455681 -1.2834764 -1.0941130
[3,] 6.4941289 6.6330879 5.88252329 7.1254892 6.88332171 7.79059098 6.9549380 6.84726299 6.9756743 6.3790811
[4,] 0.5357159 -0.0629098 0.06064112 0.3261975 -0.05377268 -0.04489599 0.1968423 0.02764062 0.2472463 -0.6944623
[5,] -0.1771154 0.1974865 0.56104333 -0.1188214 0.40202835 1.37694954 0.2904445 0.22634565 1.0650977 0.3231615
Not bad. I am doing 10,000 regressions and storing the residuals from all of them in a matrix and it takes a little over 20 seconds. Note, that this is a single threaded operation that sequentially steps through 10,000 regressions.
Well these exposures are actually genetic CpG methylation scores and I have ~ a million of them to do, so I wanted to use foreach() and doParallel to multithread this and I have been unable to figure it out.
This is what I tried. I first broke up the betas matrix into 4 named dataframes with 1/4 the columns in each part:
mylist <- list(b1 = betas[1:2500], b2 = betas[2501:5000], b3 = betas[5001:7500], b4 = betas[7501:10000])
names(mylist); length(mylist)
[1] "b1" "b2" "b3" "b4"
[1] 4
Then I tried to implement the doParallel as follows:
myresids_par <- foreach(i = 1:length(mylist), .combine = "cbind") %dopar% {
do.call(cbind, lapply(mylist[i], get_resids))
}
stopCluster(cl)
But what I got was the following; just 4 sets of residuals as follows and I'm not sure what it did:
> dim(myresids_par)
[1] 100 4
> head(myresids_par)
b1 b2 b3 b4
[1,] -1.1051559 -3.2815443 -4.0951682 -2.97181934
[2,] -1.7884883 -1.5842009 -2.2403507 -1.48095064
[3,] 6.0211664 6.8417766 7.0208282 6.93438155
[4,] -0.4692244 0.1247481 0.9653631 -0.08206986
[5,] -0.1857339 0.2945526 1.8936715 0.30034781
[6,] 8.7706564 7.9744631 8.5240021 8.05232223
The problem here is that mylist[i] is accessing a sub-list of length one (not the data frame stored in the i-th element of the list; you'll need mylist[[i]] instead).
So you can use:
myresids_par <- foreach(i = 1:length(mylist), .combine = "cbind") %dopar% {
do.call(cbind, lapply(mylist[[i]], get_resids))
}
or better, just use:
myresids_par <- foreach(i = seq_along(mylist), .combine = "c") %dopar% {
lapply(mylist[[i]], get_resids)
}
And then use do.call(cbind, myresids_par) if you want a matrix or just as.data.frame(myresids_par) if you want a data frame.
PS: note that lapply here works because a data frame is also a list. If you had matrices in your list, you would need to use apply(MAT, 2, FUN).
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
After obtaining a proximity matrix from randomForest, for each row/observation in the data set I would like to find the k-nearest points (excluding the observation itself, or, equivalently, the diagonal elements of the proximity matrix) and then their true class labels. I know how to find the indices of the max or min of each row in a matrix but I do not know how to program R to exclude the diagonal elements and to identify the k greatest entries by row.
> set.seed(1234)
> d <- iris[sample(nrow(iris), 6, replace = FALSE),]
> iris.rf <- randomForest(Species ~ ., data=d, ntree=2000, proximity=TRUE, oob.prox=TRUE)
> m <- iris.rf$proximity
> m
18 93 91 92 126 149
18 1.0000000 0.7486911 0.7653631 0.7500000 0.2620690 0.4723926
93 0.7486911 1.0000000 0.7836257 0.7329545 0.5497076 0.2763819
91 0.7653631 0.7836257 1.0000000 0.6795580 0.5371429 0.2289157
92 0.7500000 0.7329545 0.6795580 1.0000000 0.3107345 0.4535519
126 0.2620690 0.5497076 0.5371429 0.3107345 1.0000000 0.8115942
149 0.4723926 0.2763819 0.2289157 0.4535519 0.8115942 1.0000000
> which(m[1,] == max(m[1,]), arr.ind = TRUE)
18
1
I was able to solve it on my own, although if there is a way to improve the code (or if there is an error) I would appreciate the feedback.
f = function(d,k){
m <- randomForest(y ~ ., data=d, ntree=2000, proximity=TRUE, oob.prox=TRUE)$proximity
diag(m) <-0
tmp <- lapply(as.list(as.data.frame(m)),order,decreasing = TRUE)
tmp1 <- t(as.data.frame(tmp))[,c(1:k)]
class.mat <- matrix(data=NA,nrow(d), k, byrow=TRUE)
for(i in 1:nrow(d)){
class.mat[i,] = d$y[tmp1[i,]]
}
return(class.mat)
}
I want a matrix with only the correlation coefficients which are bigger than 0.2. I came up with the following solution.
mts.data <- ts(data.frame(a=arima.sim(model=list(1,0,0), n=10),
b=arima.sim(model=list(1,0,1), n=10), c=arima.sim(model=list(1,0,0),
n=10), d=arima.sim(model=list(1,0,2), n=10),
e=arima.sim(model=list(2,0,1), n=10)), start=c(2007,1), frequency=12)
critcor <- function(x) {
crit.mat <- matrix(0, nrow=ncol(x), ncol=ncol(x))
for(j in 1:ncol(x)) {
for(i in 1:ncol(x)) {
if(abs(cor(x[,i], x[,j])) > 0.2) {
crit.mat[i,j] <- cor(x[,i], x[,j])
}
}
}
return(crit.mat)
}
This works fine. Unfortunately, my data set contains missing values.
mts.data[1:3, 4] <- NA
mts.data[9:10, 5] <- NA
When I run my function, I got an error.
critcor(mts.data)
# Error in if (abs(cor(x[, i], x[, j])) > 0.2) { :
# missing value where TRUE/FALSE needed
I'm browsing the Internet for several hours now and I have absolutely no idea how I could fix this. If a correlation is not possible because of the missing values, I want my function just print a 0 instead.
You can greatly simplify your code like this:
cm = cor(mts.data, use = "p")
cm[abs(cm) <= 0.2] = 0
which gives:
> cm
a b c d e
a 1.0000000 0.0000000 -0.4667718 -0.5241904 -0.6864418
b 0.0000000 1.0000000 0.0000000 -0.3270387 0.0000000
c -0.4667718 0.0000000 1.0000000 0.4708803 0.5222566
d -0.5241904 -0.3270387 0.4708803 1.0000000 0.0000000
e -0.6864418 0.0000000 0.5222566 0.0000000 1.0000000
The snippet use = "p" is short for "pairwise complete observations", i.e. NAs will be omitted when necessary. For more options and details see ?cor.
The error you received was when you had a value that was NA. Then also the comparison NA > 0.2 will be NA and if does not accept NA as its input, thus the error.
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.