R code to find slope in Tableau - r

I tried to write the formula to get the slope using R and Tableau integration.
My formula within the calculated field shows to be a valid one. However, when I try to plot the same, I get an error. The formula i am using is as follows:
SCRIPT_REAL("mydata <- data.frame(cbind(yy = .arg1, xx = .arg2)); fit <- lm(yy ~ xx,new data=mydata); fit$coeff[[2]]",(avg([Revenue Growth])),(avg([WTI]) ))
The error i receive is :
Any help with the same would be appreciated.
Thanks.

Try this:
SCRIPT_REAL(
'mydata<- data.frame(yy=.arg1, xx=.arg2);
fit <- lm(yy~xx,mydata)$coefficients[2]',
AVG([Revenue Growth],
AVG([WTI])
)

Related

I'm having trouble getting R to calculate the VIF

The following is the input I've put in R. I'm just wondering do i need to update R or have i done something wrong?
attach(crimedat)
crimedata <- crimedat[,-2]
lm1 <- lm(Expenditure+YouthUnemploy+MatureUnemploy+Wage~CrimeRate)
vif(lm1)
Error in vif(lm1) : could not find function "vif"

What does "invalid type (closure) for variable 'variable1'" mean and how do I fix it?

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!

Problem with running emmeans (error in assign '.Last.ref_grid')

I have been having trouble with running emmeans function (from the emmeans package) whenever I try to follow up a two way between groups ANOVA with estimated marginal means.
A simple example:
library(emmeans)
library(tidyverse)
df <- tibble(fct1 = factor(rep(1:3, 10)),
fct2 = factor(rep(2:1, 15)),
DV = rnorm(30, 100, 15))
model1 <- lm(DV ~ fct1 * fct2, df)
emmeans(model1, "fct1", by = "fct2")
Returns:
Error in assign(".Last.ref_grid", object, inherits = TRUE) :
cannot change value of locked binding for '.Last.ref_grid'
No matter what data I run it on, always the same error shows up.
Thank you for any help!
This should stop it:
emm_options(save.ref_grid = FALSE)
This will keep it from saving the most recently created reference grid (or trying to, in your case). However, it may be worth trying to understand why this is happening. If you do:
.Last.ref_grid
you should see what it is that was last saved. That might be a clue. And try to delete it.

Can't plot a linear regression in R using effect_plot(): value for 'data' not found in R while

I'm trying to plot a simple linear regression model using jtools::effect_plot(model) but I always get an error message like: "Error: The variable(s) were not found in the data" or "Error: value for 'grade' not found".
I've looked at the documentation of the jtools but still don't realize what is missing.
library(jtools)
library(ggplot2)
model <- lm(grade ~ hours_studied, data = data) #or
model2 <- lm(data$grade ~ data$hours_studied)
effect_plot(model)
effect_plot(model2)
Thanks
How about this?
library(data.table)
library(jtools)
library(ggplot2)
model <- lm(grade ~ hours_studied, data = data)
effect_plot(model, pred= hours_studied)
When using the effect_plot() function, you need to provide a value for the argument 'pred' as it does not have a default one.
Please refer to documentation: https://www.rdocumentation.org/packages/jtools/versions/2.1.0/topics/effect_plot

How to get the prediction output from glmmPQL to work with performance using R?

Problem
I am using R 3.3.3 on Windows 10 (x64 bit). I get the following prediction output from the glmmPQL prediction function as follows:
library(MASS)
library(nlme)
library(dplyr)
model<-glmmPQL(a ~ b + c + d, data = trainingDataSet, family = binomial, random = list( ~ 1 | e), correlation = corAR1())
The prediction values are given as follows:
p <- predict(model, newdata=testingDataSet, type="response",level=0) (1.0)
The output it gives is as follows:
I then try to measure the performance of this output using the following code:
pr <- prediction(p, testingDataSet$a)(1.1)
It gives us the following error as follows:
Error in prediction(p, testingDataSet$a) :
Format of predictions is invalid. (1.2)
I have successfully been able to use the prediction method in R using other functions (glm,svm,nn) when the data looks something like as follows:
model<-glm(a ~ b + c + e, family = binomial(link = 'logit'), data = trainingDataSet)
p <- predict(model, newdata=testingDataSet, type="response") (1.3)
Attempts
I believe the fix to the above problem is to get it into the format shown below (1.3). I have tried the following things using R and have been failing.
I have tried casting p in 1.0 using as.numeric() and as.list() and other things. I want to get look like the p R object in 1.3. In other words, I believe the format is reason why things not working for me?
No matter what mutate or casting I try, I can't seem to get it into the form in 1.3 and image shown as desired. Especially with the index as columns features.
I'm coming up empty handed on stackoverflow and the R help files. When I use the command class(p) both tell me they are numeric.
Question
Give the above, can someone tell me how I can use R to get the output from glmmPQL in a format that the prediction function can use as shown above please?
In other words, how can I make sure the output in 1.0 can made to match the output in 1.3 in R? My attempts have failed and I would deeply appreciate someone more skilled in R to point out where I am failing?
If you use as.numeric(p) then you'll get the values you want - then the only difference is that the GLM output has names. You can add these in with something like:
p <- as.numeric(p)
names(p) <- 1:length(p)
If this doesn't work, you can use str(p) to examine the structure of the object in more depth.

Resources