I did a PCA in R and I am trying to print the rotation components. I was pretty much trying to understand a snippet I found online and I would really appreciate if somebody could help me with it. Please see below the snippet I found online:
require(stats)
prcomp(top2, scale=TRUE)
summary(prcomp(top2, scale=TRUE))
for (i in 1:15) {
top4[[i]] <- sort(survey.prcomp$rotation[,i], decreasing=TRUE)[1:4]}
top4
I am trying to print top 15 principal components and I get the "top4 object not found error". I am pretty new to R and would appreciate it if somebody could please explain it.
The snippet can be found at https://www.casact.org/pubs/forum/10spforum/Francis_Flynn.pdf
Thanks a lot!
The snippet you found does not work because there is no declared "survey.prcomp" object. "top4" is missing as well. I assume the authors missed this line:
survey.prcomp <- prcomp(top2, scale=TRUE)
And also this one:
top4 <- list()
Then, if your aim is to get first 15 rotation vectors, you can do so with survey.prcomp$rotation[,1:15]
The snippet you pasted does something different. It returns, for each of 15 main principal components, top 4 variables that have the most influence on the loadings (rotations).
In the snippet you pasted a series of variables are accessed but never assigned hence the error.
top2, survey.prcomp and top4 are never assigned, in the document you have attached the author seem have omitted those lines.
Related
So i looked into a guy's code and i saw these lines of code:
for(i in 1:getOmega(bh_w_f) + 1){
bh_w_f_qx[i] = (bh_w_f#lx[i] - bh_w_f#lx[i + 1])/bh_w_f#lx[i]
What does #lx[i] mean or do? I tried look it up on the internet but i could not find anything. Any ideas? I want to mention that these lines of code above are the first occurance of #lx[i] or lx[i] or lx alone, so no declaration before. I ran the code and it works, no error given, the function works properly.
bh_w_f_qx and bh_w_f are vectors declared before
EDIT : As said in the comments and in the first answer, bh_w_f is actually a S4 object, a lifetable made with function probs2lifetable from https://www.rdocumentation.org/packages/lifecontingencies/versions/1.3.7/topics/probs2lifetable but i could not find what lx wants to be. As i said, it's the first time that lx shows up in the code, with no external files included.
EDIT 2: Found out that the answer is in the returning format from probs2lifetable() function, that returns a lifetable class object which has lxas representing the number of lives at the beginning of age (x).
More about it here: https://www.rdocumentation.org/packages/lifecontingencies/versions/1.3.7/topics/lifetable-class
Thanks
# is the symbol used to pull attributes from S4 class objects in R. This syntax can be unusual because most people use S3 as it's simpler than S4. In the case of the code you posted, my guess is that you can get away with thinking of # as the equivalent of a $ for lists and data frames etc.
I'm trying to run a block bootstrapping function on some time series data (monthly interest rates for ~15 years).
My data is in a csv file with no header, all comprising one column and going down by row.
I installed the package bootstrap because tsboot wouldn't work for me.
Here is my code:
testFile = read.csv("\\Users\\unori/sample_data.csv")
theta <- function(x){mean(x)}
results = bootstrap(testFile,100,theta)
It tells me there are at least 50 errors. All of them say "In mean.default(x) : argument is not numeric or logical: returning NA"
What to do? It runs when I use the example in the documentation. I think it must be how my data is stored/imported?
Thanks in advance.
Try to supply a working, minimal example that reproduces your problem! Check here to see how to make a minimal reproducible example.
The error messages tells you that the thing you want to calculate the mean of, is not a number! So R will just return NA.
Suggestions for debugging:
Does the object 'testFile' exist?
What is the output of
str(testFile)
This works for me:
library(bootstrap)
testFile <- cars[,1]
theta <- function(x){mean(x)}
results = bootstrap(testFile,100,theta)
I was trying to convert the Chan code about Pairs Trading strategy with dynamic hedge ratio into R.
I have already done all work with a steady hedge, but if I want to replicate his "for" loop I'm in trouble. Here my code for that part
lookback=20
hedge=rep(NaN,length(stockY))
for (i in lookback:length(hedge)){
reg=lm(stockY[i-lookback +1:i]~stockX[i-lookback +1:i])
hedge[i]=reg[1]$coeff[2]
}
I tried many different attempts but my low level in R is pretty evident here. I'm not trying to use a "lapply" function but just a for loop. Hope someone can help me. Thanks
Ok It seems I did it. The following is my code:
lookback=20
hedge=data.frame(hedge=rep(0,length(stockY)))
for (i in lookback:length(stockY)){
reg=summary(lm(stockY[i-lookback +1:i]~stockX[i-lookback +1:i]))
hedge[i,1]=reg$coefficients[2,1]
}
So, now I'd know how to extract my residuals. I mean, I need to list all residuals from regression. Unfortunately if I write reg$residuals it returns my last 20 residuals from the last iteration of the loop. So, I tried to include another "res" vector like "hedge" but.....I can't extract my residuals. Please, can someone help me?
This is a question that has been answered in context to R, so I should have a similar solution. The problem is, my code works in R but not in Shiny ?
error source
for(i in 1:N)
{
rank_free_choice<- rank_free_choice_fn(signal_agent[i], M, gamma, omega, K,m)
website_choice<- website_choice_fn(rank_data_today,alpha,rank_free_choice)
t1<- ranking_algo_fn(rank_data_today, website_choice, kappa)
rank_data_today<- t1
df_website_choice[i,]<- website_choice
df_rank_data[i,]<- rank_data_today
}
Both matrices are initialized before the loop begins, and rank_data_today was also created before.
The function continues further, and multiple outputs are put together in a list before returning it outside the function.
Curiously I have another app that runs this code similarly, and that works fine!! In that one the initial rank data is passed to df_rank_data[i,] and the updated are passed to df_rank_data[i+1,]
Anybody with a solution? Or perhaps could explain this answer in my context?
I figured it out, and since the problem was so bizarre, I'm posting it here in case anyone else runs into a similar problem.
The reason the code wasn't working was because one of the inputs to the function was missing in Shiny!!!!!
So basically it was a plain and simple typo/carelessness but the error didn't really help.
The Shiny app is just a wrapper around a simulation I wrote in R that used functions, taking inputs from other functions. The error only showed up in the penultimate function [No real way to trace it]
It was working in R because I didn't have to separately input any values as I'd already saved the code.
I have some r code that I've used in the past to produce topic models. Everything was working fine until I updated all of my r packages in the hopes of fixing a slightly unrelated problem. Now, code which had previously worked seems to be broken and I can't figure out what to do.
I read this post and found it very helpful in setting this up originally. It describes a method of cleaning blank rows after sparse terms have been removed to set up subsequent analysis. Here is what happens when I enter the same code with my current packages:
> rowTotals <- apply(a.dtm.t, 1, sum) #Find the sum of words in each Document
> a.dtm.t.rt <- a.dtm.t[rowTotals>0]
Error in `[.simple_triplet_matrix`(a.dtm.t, rowTotals > 0) :
Logical vector subscripting disabled for this object.
Does anyone know how I can go about locating the problem, and roll back to a working solution? Thanks.
Try a.dtm.t.rt <- a.dtm.t[which(rowTotals>0)]
If that doesn't work then you need to show a reproducible example. We have no idea what anything you're doing here is.
I find the same problem as yours. I use slam package to solve this issue.
library(slam)
# take tdm as a large term-document matrix
freq <- rowapply_simple_triplet_matrix(tdm,sum)
Also the colapply_simple_triplet_matrix will help to handle the sparse matrix