R lm() weights argument being ignored when placed inside function - r

I am trying to figure out why the following piece of code ignores the weights argument and produces simply an unweighted regression analysis. If I remove the function wrapping everything works fine. The only way the code runs is if I change the code so that weights=richiu, but I really don't know why the original code would not work in a function environment. Any clear explanations would be really helpful.
set.seed(1)
UU=rnorm(1000)
ZZ=rnorm(UU)
futa=data.frame(UU,ZZ)
stringy=paste("ZZ~UU",sep="")
friga=function(stringy,futa){
richiu=rnorm(1000)
futa$richiu=richiu
print(colnames(futa))
lm(stringy,data=futa, weights=futa$richiu)
}
friga(stringy,futa=futa)
lm(ZZ~UU)

Related

error when attempting to remove values from regressionin r

I have been doing some playing around with regressors in r, however, I have run into a problem. when trying to remove coefficients from a regressor.
newRegressor$coefficients <- newRegressor$coefficients[-1]
at first, I thought that this approach succeeded, as printing the newRegressor$coefficients shows that the first coefficient has been successfully removed. This later caught me off guard however when I was using this regression later, and when error checking I realized that the first element was still their in the summary.
Is there any other way to remove the first coefficient within a regressor, without re-declaring it using the lm() function (or any other function along the same lines)?
In case of any confusion, there are no error messages. Also here are the screenshots of the coefficients of summary(newRegress) before and after running the line
newRegressor$coefficients <- newRegressor$coefficients[-6]
Before:
After:
What is the error showing? If you want to remove all rows of column 7, you can write
newRegressor$coefficients <- newRegressor$coefficients[,-7]

for Loop, replacement has length zero, Shiny

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.

For Loop with MCMCglmm Regression

I've looked at some of the answers for this question already, there were only two I found helpful and I still cannot get my loop to execute. I am struggling to use a fixed formula for the MCMCglmm package. I have a lot of models to test with this package, and I would like to make a loop to make the work easier. Each time I run MCMCglmm my intention is to do so with a "fixed" formula, and through each iteration of the loop I want to change one of the variables and input a modified version of the "fixed" formula. Here is my code thus far:
for (i in 5:10){
fixed <- as.formula(paste(as$area_pva ~ as$apva_1yr + as$year + as.numeric(unlist(as[i]))))
print(fixed)
model <- MCMCglmm(fixed=fixed,
rcov=~units, family="gaussian",
data=as,start=NULL, prior=NULL, random=NULL, tune=NULL,
pedigree=NULL, nodes=NULL, scale=FALSE, nitt=30000,
thin=30, burnin=1000, pr=TRUE, pl=TRUE, verbose=TRUE,
DIC=TRUE, singular.ok=FALSE, saveX=TRUE, saveZ=TRUE,
saveXL=TRUE, slice=FALSE, ginverse=NULL)
summary(model)
}
Please, if you can help me make this loop execute properly I would appreciate it.
Never mind, I've got the answer. I needed to make the whole formula a series of strings, like this:
fixed <- as.formula(paste("as$area_pva~as$apva_1yr+as$year+", colnames(as)[i], sep=""))
It works perfectly now.

Trying to use the baseline function with apply instead of a for loop in R

I have spectral data that I am trying to run PCA on. To learn how to do this I have created a matrix with two distinct groups and then pulled a file in that has typical wavelengths. I am pre-processing the data and have run into issues with baseline correction. I can do it with a for loop, but want to know if I can do it with apply instead. I get different errors depending on what I am trying and don't know if it is even possible. My most recent error is:
Error in matrix(0, np[1], np[2]) : non-numeric matrix extent.
I get this immediately after:
playdata.baseline<-apply(playdata,1, baseline,lambda=1,hwi=20,it=30,int=800,method='fillPeaks')
Can I use apply for the baseline function? If yes, why is it not working with the rest of the code that works fine using a for loop for baseline?
Here is what works:
#baseline corrections
playdata.baseline=matrix(0,ncol=nrow(playdata),nrow=ncol(playdata))
playdata.bc=c()
playdata=t(playdata)
for (n in 1:(length(playdata[,1]))){
playdata.bc=baseline(playdata[n,,drop=FALSE],
lambda=1, hwi=20, it=30,
int=800, method='fillPeaks')
playdata.baseline[n,]=playdata.bc#corrected
}
playdata=playdata.baseline
playdata=t(playdata)
Keeping everything the same until # baseline corrections, the apply attempt is as follows:
#baseline corrections
playdata=t(playdata)
playdata.baseline <- apply(playdata, 1, baseline, lambda=1, hwi=20,
it=30, int=800, method='fillPeaks')
playdata=t(playdata)

Use the multiple variables in function in r

I have this function
ANN<-function (x,y){
DV<-rep(c(0:1),5)
X1<-c(1:10)
X2<-c(2:11)
ANN<-neuralnet(x~y,hidden=10,algorithm='rprop+')
return(ANN)
}
I need the function run like
formula=X1+X2
ANN(DV,formula)
and get result of the function. So the problem is to say the function USE the object which was created during the run of function. I need to run trough lapply more combinations of x,y, so I need it this way. Any advices how to achieve it? Thanks
I've edited my answer, this still works for me. Does it work for you? Can you be specific about what sort of errors you are getting?
New response:
ANN<-function (y){
X1<-c(1:10)
DV<-rep(c(0:1),5)
X2<-c(2:11)
dat <- data.frame(X1,X2)
ANN<-neuralnet(DV ~y,hidden=10,algorithm='rprop+',data=dat)
return(ANN)
}
formula<-X1+X2
ANN(formula)
If you want so specify the two parts of the formula separately, you should still pass them as formulas.
library(neuralnet)
ANN<-function (x,y){
DV<-rep(c(0:1),5)
X1<-c(1:10)
X2<-c(2:11)
formula<-update(x,y)
ANN<-neuralnet(formula,data=data.frame(DV,X1,X2),
hidden=10,algorithm='rprop+')
return(ANN)
}
ANN(DV~., ~X1+X2)
And assuming you're using neuralnet() from the neuralnet library, it seems the data= is required so you'll need to pass in a data.frame with those columns.
Formulas as special because they are not evaluated unless explicitly requested to do so. This is different than just using a symbol, where as soon as you use it is evaluated to something in the proper frame. This means there's a big difference between DV (a "name") and DV~. (a formula). The latter is safer for passing around to functions and evaluating in a different context. Things get much trickier with symbols/names.

Resources