I am new in R. I am trying to impose monotonicity conditions to a translog production function. I am using the function translogMonoRestr. I loaded my data, the coeff and the inv of the var cov matrix. I imported this from excel and all good
read_excel("rtl2.xlsx")
uCoef <- read_excel("matrixbtl2.xlsx")
uCovInv <- read_excel("matrixinvtl2.xlsx")
but when I tried:
monoRestr <- translogMonoRestr( xNames, = c( "lx1", "lx2"), rtl2.xlsx , dataLogged = TRUE)
I got Error in testNames %in% allNames : object 'rtl2' not found.
Then I'll use solve.QP but that is another topic.
I hope someone can help me with this error message
Thanks
Related
I am trying to write a function in R, which contains a function from another package. The code works perfectly outside a function.
I am guessing, it might have got to do something with the package I am using (survey).
A self-contained code example:
#activating the package
library(survey)
#getting the dataset into R
tm <- read.spss("tm.sav", to.data.frame = T, max.value.labels = 5)
# creating svydesign object (it basically contains the weights to adjust the variables (~persgew: also a column variable contained in the tm-dataset))
tm_w <- svydesign(ids=~0, weights = ~persgew, data = tm)
#getting overview of the welle-variable
#this variable is part of the tm-dataset. it is needed to execute the following steps
table(tm$welle)
# data manipulation as in: taking the v12d_gr-variable as well as the welle-variable and the svydesign-object to create a longitudinal variable which is transformed into a data frame that can be passed to ggplot
t <- svytable(~v12d_gr+welle, tm_w)
tt <- round(prop.table(t,2)*100, digits=0)
v12d <- tt[2,]
v12d <- as.data.frame(v12d)
this is the code outside the function, working perfectly. since I have to transform quite a few variables in the exact same way, I aim to create a function to save up some time.
The following function is supposed to take a variable that will be transformed as an argument (v12sd2_gr).
#making sure the survey-object is loaded
tm_w <- svydesign(ids=~0, weights = ~persgew, data = data)
#trying to write a function containing the code from above
ltd_zsw <- function(variable1){
t <- svytable(~variable1+welle, tm_w)
tt <- round(prop.table(t,2)*100, digits=0)
var_ltd_zsw <- tt[2,]
var_ltd_zsw <- as.data.frame(var_ltd_zsw)
return(var_ltd_zsw)
}
Calling the function:
#as v12d has been altered already, I am trying to transform another variable v12sd2_gr
v12sd2 <- ltd_zsw(v12sd2_gr)
Console output:
Error in model.frame.default(formula = weights ~ variable1 + welle, data = model.frame(design)) :
invalid type (closure) for variable 'variable1'
Called from: model.frame.default(formula = weights ~ variable1 + welle, data = model.frame(design))
How do I fix it? And what does it mean to dynamically build a formula and reformulating?
PS: I hope it is the appropriate way to answer to the feedback in the comments.
Update: I think I was able to trace the problem back to the argument I am passing (variable1) and I am guessing it has got something to do with the fact, that I try to call a formula within the function. But when I try to call the svytable with as.formula(svytable(~variable1+welle, tm_w))it still doesn't work.
What to do?
I have found a solution to the problem.
Here is the tested and working function:
ltd_test <- function (var, x, string1="con", string2="pro") {
print (table (var))
x$w12d_gr <- ifelse(as.numeric(var)>2,1,0)
x$w12d_gr <- factor(x$w12d_gr, levels = c(0,1), labels = c(string1,string2))
print (table (x$w12d_gr))
x_w <- svydesign(ids=~0, weights = ~persgew, data = x)
t <- svytable(~w12d_gr+welle, x_w)
tt <- round(prop.table(t,2)*100, digits=0)
w12d <- tt[2,]
w12d <- as.data.frame(w12d)
}
The problem appeared to be caused by the svydesgin()-fun. In its output it produces an object which is then used by the formula for svytable()-fun. Thats why it is imperative to first create the x_w-object with svydesgin() and then use the svytable()-fun to create the t-object.
Within the code snippet I posted originally in the question the tm_w-object has been created and stored globally.
Thanks for the help to everyone. I hope this is gonna be of use to someone one day!
I am getting a Error in 1:T : argument of length 0 when running the Performance Analytics package in R. am I missing a package? Below is my code with error.
#clean z, all features, alpha = .01, run below
setwd("D:/LocalData/casaler/Documents/R/RESULTS/PLOTS_PCA/CLN_01")
PGFZ_ALL <- read.csv("D:/LocalData/casaler/Documents/R/PG_DEUX_Z.csv", header=TRUE)
options(max.print = 100000) #Sets ability to view all dealer records
pgfzc_all <- PGFZ_ALL
#head(pgfzc_all,10)
library("PerformanceAnalytics")
library("RGraphics")
Loading required package: grid
pgfzc_elev <- pgfzc_all$ELEV
#head(pgfzc_elev,5)
#View(pgfzc_elev)
set.seed(123) #for replication purposes; always use same seed value
cln_elev <- clean.boudt(pgfzc_elev, alpha = 0.01) #set alpha .001 to give the most extreme outliers
Error in 1:T : argument of length 0
It's hard to answer your question without knowing what your data looks like. But I can tell you what throws that error. Looking into the source code of the clean.boudt function I find the following cause of your error:
T = dim(R)[1]
...
for (t in c(1:T)) {
d2t = as.matrix(R[t, ] - mu) %*% invSigma %*% t(as.matrix(R[t,
] - mu))
vd2t = c(vd2t, d2t)
}
...
The dim(R)[1] extracts the number of rows in the data supplied to the R argument in the function. It appears that your data has no rows, so check the data type of pgfzc_elev
The cause of the error is likely from your use of $ to subset pgfzc_all.
pgfzc_elev <- pgfzc_all$ELEV
I reckon it is of class integer, which is why dim(R)[1] does not work in the function.
Rather subset your object like this:
pgfzc_elev <- pgfzc_all[, ELEV, drop = F]
Try that and see if it works.
The moment condition function is simply exp(-g/r)-1, where g is a known series of daily return on AAA-class bond index, and r is the rikiness measure to be derived through gmm. My codes are as follows:
View(Source)
library(gmm)
data(Source)
x <- Source[1:5200,"AAA"]
m <- function(r,x)
{m.1 <- exp(-x[,"AAA"]/r)-1}
summary(gmm(m,x,t0=1,method="BFGS",control=1e-12))
Which in term yields the following error message:
****Error in model.frame.default(formula = gmat ~ 1, drop.unused.levels = TRUE) :
invalid type (list) for variable 'gmat'****
Could anyone help me figure out what went wrong?
Thanks a lot!
For those kind people who would like to replicate the results, please find attached the source data as mentioned above.
The correct r is 1.590 , which can be solved through goal searching in excel, with target function :(average(exp(-g/r)-1) )^2 and target value: 0 (tolerance: 1e-12)
https://docs.google.com/spreadsheets/d/1AnTErQd2jm9ttKDZa7On3DLzEZUWaz5Km3nKaB7K18o/edit?usp=sharing
I've spent a lot of time trying to solve this error and searching for solutions without any luck, and I thank you in advance for your help.
I'm trying to create predicted values from the coefficients created via BMA. Whenever I run my predict function, I am getting a "newdata is missing variables" error. All variables included in the original model are present in the new dataframe, so I'm not quite sure what the problem is. I'm working with a fairly large dataset with many independent variables. I'm fairly new to R, so I apologize if this is an obvious question!
y<-df$y
x<-df
x$y<-NULL
bic.glm<-bic.glm(x, y, strict=FALSE, OR=20, glm.family="binomial", factortype=TRUE)
predict(bic.glm.bwt, x)
I've also tried it this way:
bic.glm<-bic.glm(y~., data=df, strict=FALSE, OR=20, glm.family="binomial", factortype=TRUE)
predict(bic.glm, x)
And also with creating a new data frame...
bic.glm<-bic.glm(y~., data=df, strict=FALSE, OR=20, glm.family="binomial", factortype=TRUE)
newdata<-x
predict(bic.glm, newdata=x)
Each time I receive the same error message:
Error in predict.bic.glm(bic.glm, newdata=x) :
newdata is missing variables
Any help is very much appreciated!
First, it is bad practice to call your LHS the same name as the function call. You may be masking the function bic.glm from further use.
That minor comment aside... I just encountered the same error. After some digging, it seems that predict.bic.glm checks the names vs. the mle matrix in the bic.glm object. The problem is that somewhere in bic.glm, if factors are used, those names get a '.x' or just '.' appended at the end. Therefore, whenever you use factors you will get this error.
I communicated this to package maintainers. Meanwhile, you can work around the bug by renaming the column names of the mle object, like this (using your example):
fittedBMA<-bic.glm(y~., data=df)
colnames(fittedBMA$mle)=colnames(model.matrix(y~., data=df)) ### this is the workaround
predict(fittedBMA,newdata=x) ### should work now, if x has the same variables as df
Okay, so first look at the usage section in the cran documentation for BMA::bic.glm.
here
This example is instructive for a data.frame.
Example 2 (binomial)
library(MASS)
data(birthwt)
y <- birthwt$lo
x <- data.frame(birthwt[,-1])
x$race <- as.factor(x$race)
x$ht <- (x$ht>=1)+0
x <- x[,-9]
x$smoke <- as.factor(x$smoke)
x$ptl <- as.factor(x$ptl)
x$ht <- as.factor(x$ht)
x$ui <- as.factor(x$ui)
bic.glm.bwT <- bic.glm(x, y, strict = FALSE, OR = 20,
glm.family="binomial",
factor.type=TRUE)
predict( bic.glm.bwT, newdata = x)
bic.glm.bwF <- bic.glm(x, y, strict = FALSE, OR = 20,
glm.family="binomial",
factor.type=FALSE)
predict( bic.glm.bwF, newdata = x)
I'm trying to write a function for a task I need to do many times (running a cox proportional hazards function over multiple imputed datasets). When I pass the necessary objects to my user-defined function, however, it gives an error, stating that the object cannot be found. I think this is because the object is defined within a dataframe that is specified with the "data=" argument within the cch() function. Can anyone help me with this?
Example data:
my.list<-list(my.df1 <- data.frame(my.id = 1:100, my.time = rlnorm(100),
my.event= c(rbinom(50,1,0.2),rep(1,50)), my.det=rbinom(100,1,0.5),
sub= c(rep(1,50), rbinom(50, 1, 0.1))), my.df2 <- data.frame(my.id = 1:100,
my.time = rlnorm(100), my.event= c(rbinom(50,1,0.2),rep(1,50)),
my.det=rbinom(100,1,0.5), sub= c(rep(1,50), rbinom(50, 1, 0.1))))
Outside my user-defined function, this works:
library(KMsurv)
library(survival)
cch(Surv(my.time,my.event)~as.factor(my.det), data=my.df1, subcoh=~sub,
id=~my.id, cohort.size=500)
However, this does not work (this is an example function, not the real function as the real function is more complex and runs analyses on multiple datasets, then combines them):
myfun<-function(dflist,time,event){
for (i in 1:length(dflist)){
out<-cch(Surv(time,event)~as.factor(my.det), data=dflist[[i]],
subcoh=~sub, id=~my.id, cohort.size=500)
print(out)}
}
myfun(my.list,my.time,my.event)
I get this error: "Error in Surv(time, event) : object 'my.time' not found".
I found some posts about using an eval(substitute()) function to deal with a similar problem, but I can't get it to work. Any suggestions are greatly appreciated!
Try this. You need to keep in mind that R doesn't know what's my.time and my.event. You have to parse them with quotes and then unqoute them in order to parse it into Surv
myfun<-function(dflist,time,event){
for (i in 1:length(dflist)){
time <- noquote(time)
event <- noquote(event)
out<-cch(Surv(dflist[[i]][, time], dflist[[i]][, event])~as.factor(my.det), data=dflist[[i]],
subcoh=~sub, id=~my.id, cohort.size=500)
print(out)}
}
myfun(my.list,"my.time","my.event")