I have data of this form:
x y
1 0.19
2 0.26
3 0.40
4 0.58
5 0.59
6 1.24
7 0.68
8 0.60
9 1.12
10 0.80
11 1.20
12 1.17
13 0.39
I'm currently plotting a kernel-smoothed density estimate of the x versus y using this code:
smoothed = ksmooth( d$resi, d$score, bandwidth = 6 )
plot( smoothed )
I simply want a plot of the x versus smoothed(y) values, which is ## Heading ##
However, the documentation for ksmooth suggests that this isn't the best kernel-smoothing package available:
This function is implemented purely
for compatibility with S, although it
is nowhere near as slow as the S
function. Better kernel smoothers are
available in other packages.
What other kernel smoothers are better and where can these smoothers be found?
If you "simply want a plot of the x versus smoothed(y)", then I recommend considering loess in package stats - it's simple, fast and effective. If instead you really want a regression based on kernel smoothing, then you could try locpoly in package KernSmooth or npreg in package np.
Related
Context
When conducting a Randomized-Controlled Trial (RCT), some participants are randomly assigned to a treatment condition, and others to a control group. However, not everyone assigned to the treatment might follow the treatment protocol (called "treatment compliance").
According to Sagarin et al. (2014), one sensible approach to address this problem is using the complier average causal effect (CACE), also sometimes known as Local average treatment effect (LATE). According to Wikipedia, it is "the treatment effect for the subset of the sample that takes the treatment if and only if they were assigned to the treatment, otherwise known as the compliers." In other words, it will be useful if a proportion of your participants assigned to the treatment group did not follow the treatment protocol.
Question
How do you run this analysis in R?
I couldn't find anything precise on this from Google and stackoverflow searches.
Also despite my many readings, I still cannot figure out what the expected outcome is supposed to be. When using CACE, what is the outcome? Do you end up with updated scores/data ajusted for treatment non-compliance that you can just plug in your regular analyses (akin to factor scores)? Or do you simply get some kind of number that you have to do something with?
What I've tried
The eefAnalytics package seems to provide the most convenient function for this: caceSRTBoot(). "caceSRTBoot performs exploraty CACE analysis of simple randomised education trials." It allows to specify compliance through a simple compliance percentage (beautifully simple and convenient).
However, I am experiencing some problems installing the eefAnalytics package while trying to test it to see the kind of output it gives:
install.packages("eefAnalytics")
package ‘eefAnalytics’ is not available (for R version 4.0.2)
# Install the latest version of this package by entering the following in R:
install.packages("eefAnalytics", repos="http://R-Forge.R-project.org")
package ‘eefAnalytics’ is not available (for R version 4.0.2)
Warning in install.packages :
unable to access index for repository http://R-Forge.R-project.org/bin/windows/contrib/4.0:
cannot open URL 'http://R-Forge.R-project.org/bin/windows/contrib/4.0/PACKAGES'
Upon closer investigation, Cran says: "Package ‘eefAnalytics’ was removed from the CRAN repository."
The other packages I've looked at (e.g., 1, 2, 3, 4) seemed quite complicated and I couldn't figure them out (they don't have a parameter for % compliance for instance, and I had trouble making their "Run this example" widget work). Is there any other user-friendly package out there? Is there any other way to do this analysis in R? Would anyone have some kind of "tutorial"?
Relevant pages: 1.
Installing the eefAnalytics package
I contacted the eefAnalytics package maintainer through the package documentation. I was told that an updated version will be available soon in R. In the meanwhile, I was able to install the old version of the package from the CRAN archives with:
install.packages("https://cran.r-project.org/src/contrib/Archive/eefAnalytics/eefAnalytics_1.0.6.tar.gz", repos = NULL, type = "source")
Note, however, that I had to manually install packages geoR and metafor separately first (else it was throwing an error).
Running the Causal Average Treatment Effect
Answering the first part of the question:
How do you run this analysis in R?
Running the example available from documentation for a simple randomised trial, we get:
library(eefAnalytics)
data(mstData)
############# weighted ITT ####################################
caceOutput3 <- caceSRTBoot(Posttest~ Prettest+ Intervention,
intervention="Intervention",
compliance = "Percentage_Attendance",nBoot=1000,data=mstData)
cace <- caceOutput3$CACE
cace
Compliance ES LB UB
1 P> 0 0.32 0.04 0.62
2 P> 10 0.32 0.04 0.62
3 P> 20 0.37 0.04 0.72
4 P> 30 0.42 0.05 0.83
5 P> 40 0.47 0.06 0.92
6 P> 50 0.58 0.07 1.18
Complier <- caceOutput3$Compliers
Complier
P > 0 P > 10 P > 20 P > 30 P > 40 P > 50 P > 60 P > 70 P > 80 P > 90
pT 1 1 0.87 0.75 0.69 0.55 0.41 0.31 0.25 0.15
pC 0 0 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00
P=PT-pC 1 1 0.87 0.75 0.69 0.55 0.41 0.31 0.25 0.15
### visualising CACE effect size
plot(caceOutput3)
Interpretation of output
I couldn’t find this information from the package documentation, but from what I understand from the output:
ITT = intent to treat
ES = effect size (Hedge’s g)
LB = lower-bound (of the confidence interval of the effect size)
UB = upper-bound
pT = Percentage of compliers in Treatment group
pC = Percentage of compliers in Control group
P=PT-pC = Percentage of compliers in Treatment group minus Percentage of compliers Control group
P > X = Value for participants with a percentage of compliance greater than X (e.g., 50%)
What is the outcome?
To answer the second part of the question:
When using CACE, what is the outcome?
The main outcome of interest seems to be an adjusted effect size (Hedge's g, which is similar to Cohen's d but better for small sample sizes < 20). It seems only possible to compare two groups together, not more (as Hedge's g, like Cohen's d, can only compare two means at once).
The plot is very useful and allows to see the "improvement" of the effect size as a function of increasing compliance with treatment. What you see in this example is that a higher compliance percentage leads to larger effect sizes, as expected.
I want to simulate 100 data with 5 columns. I want to get a correlation of 0.5 between the columns. To complete it, I have done the following action
F1 <- matrix( c(1, .5, .5, .5,.5,
.5, 1, .5, .5,.5,
.5, .5, 1, .5,.5,
.5, .5, .5, 1,.5,
.5, .5, .5, .5,1
), 5,5)
To simulate the intended data frame, I have done this, but it does not work properly.
df2 <- as.data.frame (rbinom(100, 1,.5),ncol(5), F1)
I'm surprised this isn't a duplicate (this question refers specifically to non-binary responses, i.e. binomial with N>1). The bindata package does what you want.
library(bindata)
## set up correlation matrix (compound-symmetric with rho=0.5)
m <- matrix(0.5,5,5)
diag(m) <- 1
Simulate with a mean of 0.5 (as in your example):
set.seed(101)
## this simulates 10 rather than 100 realizations
## (I didn't read your question carefully enough)
## but it's easy to change
r <- rmvbin(n=10, margprob=rep(0.5,5), bincorr=m)
round(cor(r),2)
Results
1.00 0.22 0.80 0.05 0.22
0.22 1.00 0.00 0.65 1.00
0.80 0.00 1.00 -0.09 0.00
0.05 0.65 -0.09 1.00 0.65
0.22 1.00 0.00 0.65 1.00
this looks wrong - the correlations aren't exactly 0.5 - but on average they will be (when I sampled 10,000 vectors rather than 10, the values ranged from about 0.48 to 0.51). Equivalently, if you simulated many samples of 10 and computed the correlation matrix for each, you should find that the expected (average) correlation matrix is correct.
simulating values with correlation exactly equal to the specified value is much harder (and not necessarily what you want to do anyway, depending on the application)
note that there will be limitations about what mean vectors and correlation matrices are feasible. For example, the off-diagonal elements of an n-by-n compound-symmetric (equal-correlation) matrix can't be less than -1/(n-1). Similarly, there may be limits on what correlations are possible for a given set of means (this may be discussed in the technical reference, I haven't checked).
The reference for this method is
Leisch, Friedrich and Weingessel, Andreas and Hornik, Kurt (1998) On the generation of correlated artificial binary data. Working Papers SFB "Adaptive Information Systems and Modelling in Economics and Management Science", 13. SFB Adaptive Information Systems and Modelling in Economics and Management Science, WU Vienna University of Economics and Business, Vienna. https://epub.wu.ac.at/286/
I have been presented with a problem, regarding the minimization of the absolute error, the problem know as LAD(Least absolute deviation) but, being each regressor the result of expensive test with an associated cost, one should refrain from using regressors that don't explain variance to a high degree. It takes the following equations:
Where N is the total number of observations, E the deviation associated with observation i, S the number of independant variables, lambda a penalty coefficient for the cost, and C the cost associated with performing the test.
So far, I have oriented as usual. To make it lineal, I transformed the absolute value in two errors, e^+ and e^-, where e= y_i-(B_0+sum(B_j*X_ij) and the following constraints:
z_j ={0,1}, binary value about whether the regressor enters my model.
B_i<=M_zj; B_i>=-M_zj
E^+, E^- >=0
A toy subset of data I'm working has the following structure:
For y
quality
1 5
2 5
3 5
4 6
5 7
6 5
For the regressors
fixed.acidity volatile.acidity citric.acid
1 7.5 0.610 0.26
2 5.6 0.540 0.04
3 7.4 0.965 0.00
4 6.7 0.460 0.24
5 6.1 0.400 0.16
6 9.7 0.690 0.32
And for the cost
fixed.acidity volatile.acidity citric.acid
1 0.26 0.6 0.52
So far, my code looks like this:
# loading the matrixes
y <- read.csv(file="PATH\\y.csv", header = TRUE, sep = ",") #dim=100*11
regresores <- read.csv(file="PATH\\regressors.csv", header = TRUE, sep = ",")#dim=100*1
cost <- read.csv(file="PATH\\cost.csv", header = TRUE, sep = ",")#dim=1*11
for (i in seq(0, 1, by = 0.1)){#so as to have a collection of models with different penalties
obj.fun <- c(1,1,i*coste)
constr <- matrix(
c(y,regresores,-regresores),
c(-y,-regresores,regresores),
sum(regresores),ncol = ,byrow = TRUE)
constr.dir <- c("<=",">=","<=","==")
rhs<-c(regresores,-regresores,1,binary)
sol<- lp("min", obj.fun, constr, constr.tr, rhs)
sol$objval
sol$solution}
I know theres is a LAD function in R, but for consistence sake with my colleagues, as well as a pretty annoying phD tutor, I have to perform this using lpSolve in R. I have just started with R for the project and I don't know exactly why this won't run. Is there something wrong with the syntax or my formulation of the model. Right know, the main problem I have is:
"Error in matrix(c(y, regressors, -regressors), c(-y, -regressors, regressors), : non-numeric matrix extent".
Mainly, I intended for it to create said weighted LAD model and have it return the different values of lambda, from 0 to 1 in a 0.1 step.
Thanks in advance and sorry for any inconvenience, neither English nor R are my native languages.
file.data has the following values to fit with Weibull distribution,
x y
2.53 0.00
0.70 0.99
0.60 2.45
0.49 5.36
0.40 9.31
0.31 18.53
0.22 30.24
0.11 42.23
Following the Weibull distribution function f(x)=1.0-exp(-lambda*x**n), it is giving error:
fit f(x) 'data.dat' via lambda, n
and finally plotting f(x) and xy graph have large discrepancy.
Any feedback would be highly appreciated. Thanks!
Several things:
You must skip the first line (if it really is x y).
You must use the correct function (the pdf and not the CDF, see http://en.wikipedia.org/wiki/Weibull_distribution, like you did in https://stackoverflow.com/q/20336051/2604213)
You must use an additional scaling parameter, because your data are not normalized
You must select adequate initial values for the fitting.
The following works fine:
f(x) = (x < 0 ? 0 : a*(x/lambda)**(n-1)*exp(-(x/lambda)**n))
n = 0.5
a = 100
lambda = 0.15
fit f(x) 'data.dat' every ::1 via lambda, n, a
set encoding utf8
plot f(x) title sprintf('λ = %.2f, n = %.2f', lambda, n), 'data.dat' every ::1
That gives (with 4.6.4):
If that's the actual command you provided to gnuplot, it won't work because you haven't yet defined f(x).
When I use the principal function, like in the following code, I get a nice table which gives all the standardized loadings, as well as a table with the eigenvalues and the proportion and cumulative proportion explained.
rotatedpca <- principal(PCFdataset, nfactors = 8, rotate = "varimax", scores = T)
I would like to export this output to an excel file (using WriteXLS), but I can only do that for dataframes, and rotatedpca is not a dataframe and cannot be coerced into one it seems. I am able to extract the standardized loadings by using the following code:
loadings<-as.data.frame(unclass(rotatedpca$loadings))
But I cannot figure out how to access the other information that normally displays when I simply call the principal function, in particular the eigenvalues and the proportion and cumulative variance explained. I tried rotatedcpa$values, but that returns what looks like the eigenvalues for all 12 original variables as factors without rotation, which I don't understand. And I haven't been able to figure out any way to even try to extract the variance explained values. How can I simply create a dataframe that looks like the R output I get below from the principal function, for example?
RC2 RC3 RC8 RC1 RC4 RC5 RC6 RC7
SS loadings 1.52 1.50 1.45 1.44 1.01 1.00 0.99 0.98
Proportion Var 0.13 0.12 0.12 0.12 0.08 0.08 0.08 0.08
Cumulative Var 0.13 0.25 0.37 0.49 0.58 0.66 0.74 0.82
Proportion Explained 0.15 0.15 0.15 0.15 0.10 0.10 0.10 0.10
Cumulative Proportion 0.15 0.31 0.45 0.60 0.70 0.80 0.90 1.00
Thanks for reading my post!
I have just added this feature to the latest (as of today) release of psych 1.3.10.11.
If you either
f3 <- fa(Thurstone,3)
#or
p3 <- principal(Thurstone,3)
#then
p <- print(f3)
p # will give you
p
$Vaccounted
MR1 MR2 MR3
SS loadings 2.6411150 1.8621522 1.4951831
Proportion Var 0.2934572 0.2069058 0.1661315
Cumulative Var 0.2934572 0.5003630 0.6664945
Proportion Explained 0.4402995 0.3104389 0.2492616
Proportion 0.4402995 0.7507384 1.0000000
In general, if you have suggestions or questions re the psych package, you will get a faster answer if you contact me directly.
Bill
Why not this:
capture.output( print(rotatedpca), file="pc.txt")
You can read desired portions into Excel using its Text to Columns... function off the /Data menu. Or you can just paste it into an open blank Excel document and select the rows you want to convert. Use the "fixed" option that will probably be offered automagically.