Errors in R Histogram - r

Can anyone understand why this block of code isn't producing a histogram? Here is the code:
incremental <- c()
for (i in 1:1000) {
set.seed(42)
avg_2 = mean(runif(100))
incremental <- rbind(incremental, c(avg_2))
}
incremental <- as.numeric(incremental)
hist(incremental, main = "Histogram of Averages From For Loop",
xlab = "Averages")
Don't worry about the set.seed, it is part of the exercise. All the data points will be the same, but nothing shows up on the histogram. Why is this so? Here is a screenshot of the histogram:

Actually, you are just looking at a plot with one big bar. It's very hard for R (or anyone) to guess where to create breaks if you only observe one value. Maybe you want something like this:
hist(incremental, main = "Histogram of Averages From For Loop",
xlab = "Averages",
breaks=seq(0,1, length.out=10))
This tells hist() to create 10 breaks in the range from 0 to 1.

Related

R statistical Programing

I am trying to write R codes for the histogram plot and save each histogram separate file using the following command.
I have a data set "Dummy" and i want to plot each histogram by a column name and there will be 100 histogram plots in total...
I have the following R codes that draws the each Histogram...
library(ggplot2)
i<-1
for(i in 1:100)
{
jpeg(file="d:/R Data/hist.jpeg", sep=",")
hist(Dummy$colnames<-1, ylab= "Score",ylim=c(0,3),col=c("blue"));
dev.off()
i++
if(i>100)
break()
}
As a start, let's get your for loop into R a little better by taking out the lines trying to change i, your for loop will do that for you.
We'll also include a file= value that changes with each loop run.
for(i in 1:100)
{
jpeg(file = paste0("d:/R Data/hist", i, ".jpeg"))
hist(Dummy[[i]], ylab = "Score", ylim = c(0, 3), col = "blue")
dev.off()
}
Now we just need to decide what you want to plot. Will each plot be different? How will each plot extract the data it needs?
EDIT: I've taken a stab at what you're trying to do. Are you trying to take each of 100 columns from the Dummy dataset? If so, Dummy[[i]] should achieve that (or Dummy[,i] if Dummy is a matrix).

Assigning "beanplot" object to variable in R

I have found that the beanplot is the best way to represent my data. I want to look at multiple beanplots together to visualize my data. Each of my plots contains 3 variables, so each one looks something like what would be generated by this code:
library(beanplot)
a <- rnorm(100)
b <- rnorm(100)
c <- rnorm(100)
beanplot(a, b ,c ,ylim = c(-4, 4), main = "Beanplot",
col = c("#CAB2D6", "#33A02C", "#B2DF8A"), border = "#CAB2D6")
(Would have just included an image but my reputation score is not high enough, sorry)
I have 421 of these that I want to put into one long PDF (EDIT: One plot per page is fine, this was just poor wording on my part). The approach I have taken was to first generate the beanplots in a for loop and store them in a list at each iteration. Then I will use the multiplot function (from the R Cookbook page on multiplot) to display all of my plots on one long column so I can begin my analysis.
The problem is that the beanplot function does not appear to be set up to assign plot objects as a variable. Example:
library(beanplot)
a <- rnorm(100)
b <- rnorm(100)
plot1 <- beanplot(a, b, ylim = c(-5,5), main = "Beanplot",
col = c("#CAB2D6", "#33A02C", "#B2DF8A"), border = "#CAB2D6")
plot1
If you then type plot1 into the R console, you will get back two of the plot parameters but not the plot itself. This means that when I store the plots in the list, I am unable to graph them with multiplot. It will simply return the plot parameters and a blank plot.
This behavior does not seem to be the case with qplot for example which will return a plot when you recall the stored plot. Example:
library(ggplot2)
a <- rnorm(100)
b <- rnorm(100)
plot2 <- qplot(a,b)
plot2
There is no equivalent to the beanplot that I know of in ggplot. Is there some sort of workaround I can use for this issue?
Thank you.
You can simply open a PDF device with pdf() and keep the default parameter onefile=TRUE. Then call all your beanplot()s, one after the other. They will all be in one PDF document, each one on a separate page. See here.

How to plot several violin plots in one panel as a function of time in R using lattice?

Here's a minimal example of my data and the plot I was able to adapt from this tutorial:
require(lattice)
t <- c(0.88,3.52,7.04,10.56,18.48,29.92,29.6,52.8,70.4)
n <- 1000
mu.A <- c(0.4014165,0.2444396,0.2200015,0.1829841,0.2087899,0.1385284,0.2150571,0.2272082,0.1643309 )
mu.C <- c(0.4670488,0.3561108,0.1957407,0.1564677,0.1199911,0.1883665,0.1678103,0.1194251,0.1274065 )
C <- A <- numeric(0)
for (i in 1:length(mu.C)) {C <- c(C,rnorm(mu.C[i],sd=0.031))}
for (i in 1:length(mu.A)) {A <- c(A,rnorm(mu.C[i],sd=0.021))}
data.f <- data.frame(C,A,rep(t,each=n))
colnames(data.f) <- c("C","A","Time")
bwplot(C + A ~ factor(Time),
data=data.f,
xlab="Time",
ylab="P. Estimate",
outer=T, # This parameter makes sure that the right hand side variable gets an own panel
as.table=T,
panel = function(...,box.ratio) {
panel.violin(...,col="lightblue",
box.ratio=box.ratio)
panel.bwplot(...,box.ratio=.1,pch="|")
},
par.settings = list(box.rectangle=list(col="black"),
plot.symbol=list(pch=".",cex=.001),
strip=strip.custom(factor.levels=c("C","A"))
)
)
Here's my problem: This plot doesn't have a proper time axis. It treats each element of t as a category of its own and not as a point on a continuous scale. In the experiment, time was measured and t are mean response time over all participants.
My approach here was to use xyplot() and use panel.violin as the panel function. However, this is not working. In the output, the violins are oriented horizontally and really huge. R also takes a very long time to draw the plot and eventually I have to kill the R-Studio session:
xyplot(C + A ~ Time,
data=data.f,
xlab="Time",
ylab="P. Estimate",
panel = function(...) {
panel.violin(...,col="lightblue")
},
par.settings = list(box.rectangle=list(col="black"),
plot.symbol=list(pch=".",cex=.001),
strip=strip.custom(factor.levels=c("C","A"))
)
)
I'm not so much looking for someone who just solves the problem for me but rather tells me where I'm making the mistake.
Disclaimer: This is not my real data. It's just a more convenient way to reproduce the data without having to upload it somewhere.

function lines() is not working

I have a problem with the function lines.
this is what I have written so far:
model.ew<-lm(Empl~Wage)
summary(model.ew)
plot(Empl,Wage)
mean<-1:500
lw<-1:500
up<-1:500
for(i in 1:500){
mean[i]<-predict(model.ew,data.frame(Wage=i*100),interval="confidence",level=0.90)[1]
lw[i]<-predict(model.ew,data.frame(Wage=i*100),interval="confidence",level=0.90)[2]
up[i]<-predict(model.ew,data.frame(Wage=i*100),interval="confidence",level=0.90)[3]
}
plot(Wage,Empl)
lines(mean,type="l",col="red")
lines(up,type="l",col="blue")
lines(lw,type="l",col="blue")
my problem i s that no line appears on my plot and I cannot figure out why.
Can somebody help me?
You really need to read some introductory manuals for R. Go to this page, and select one that illustrates using R for linear regression: http://cran.r-project.org/other-docs.html
First we need to make some data:
set.seed(42)
Wage <- rnorm(100, 50)
Empl <- Wage + rnorm(100, 0)
Now we run your regression and plot the lines:
model.ew <- lm(Empl~Wage)
summary(model.ew)
plot(Empl~Wage) # Note. You had the axes flipped here
Your first problem was that you flipped the axes. The dependent variable (Empl) goes on the vertical axis. That is the main reason you didn't get any lines on the plot. To get the prediction lines requires no loops at all and only a single plot call using matlines():
xval <- seq(min(Wage), max(Wage), length.out=101)
conf <- predict(model.ew, data.frame(Wage=xval),
interval="confidence", level=.90)
matlines(xval, conf, col=c("red", "blue", "blue"))
That's all there is to it.

How to draw lines on a plot in R?

I need to draw lines from the data stored in a text file.
So far I am able only to draw points on a graph and i would like to have them as lines (line graph).
Here's the code:
pupil_data <- read.table("C:/a1t_left_test.dat", header=T, sep="\t")
max_y <- max(pupil_data$PupilLeft)
plot(NA,NA,xlim=c(0,length(pupil_data$PupilLeft)), ylim=c(2,max_y));
for (i in 1:(length(pupil_data$PupilLeft) - 1))
{
points(i, y = pupil_data$PupilLeft[i], type = "o", col = "red", cex = 0.5, lwd = 2.0)
}
Please help me change this line of code:
points(i, y = pupil_data$PupilLeft[i], type = "o", col = "red")
to draw lines from the data.
Here is the data in the file:
PupilLeft
3.553479
3.539469
3.527239
3.613131
3.649437
3.632779
3.614373
3.605981
3.595985
3.630766
3.590724
3.626535
3.62386
3.619688
3.595711
3.627841
3.623596
3.650569
3.64876
By default, R will plot a single vector as the y coordinates, and use a sequence for the x coordinates. So to make the plot you are after, all you need is:
plot(pupil_data$PupilLeft, type = "o")
You haven't provided any example data, but you can see this with the built-in iris data set:
plot(iris[,1], type = "o")
This does in fact plot the points as lines. If you are actually getting points without lines, you'll need to provide a working example with your data to figure out why.
EDIT:
Your original code doesn't work because of the loop. You are in effect asking R to plot a line connecting a single point to itself each time through the loop. The next time through the loop R doesn't know that there are other points that you want connected; if it did, this would break the intended use of points, which is to add points/lines to an existing plot.
Of course, the line connecting a point to itself doesn't really make sense, and so it isn't plotted (or is plotted too small to see, same result).
Your example is most easily done without a loop:
PupilLeft <- c(3.553479 ,3.539469 ,3.527239 ,3.613131 ,3.649437 ,3.632779 ,3.614373
,3.605981 ,3.595985 ,3.630766 ,3.590724 ,3.626535 ,3.62386 ,3.619688
,3.595711 ,3.627841 ,3.623596 ,3.650569 ,3.64876)
plot(PupilLeft, type = 'o')
If you really do need to use a loop, then the coding becomes more involved. One approach would be to use a closure:
makeaddpoint <- function(firstpoint){
## firstpoint is the y value of the first point in the series
lastpt <- firstpoint
lastptind <- 1
addpoint <- function(nextpt, ...){
pts <- rbind(c(lastptind, lastpt), c(lastptind + 1, nextpt))
points(pts, ... )
lastpt <<- nextpt
lastptind <<- lastptind + 1
}
return(addpoint)
}
myaddpoint <- makeaddpoint(PupilLeft[1])
plot(NA,NA,xlim=c(0,length(PupilLeft)), ylim=c(2,max(PupilLeft)))
for (i in 2:(length(PupilLeft)))
{
myaddpoint(PupilLeft[i], type = "o")
}
You can then wrap the myaddpoint call in the for loop with whatever testing you need to decide whether or not you will actually plot that point. The function returned by makeaddpoint will keep track of the plot indexing for you.
This is normal programming for Lisp-like languages. If you find it confusing you can do this without a closure, but you'll need to handle incrementing the index and storing the previous point value 'manually' in your loop.
There is a strong aversion among experienced R coders to using for-loops when not really needed. This is an example of a loop-less use of a vectorized function named segments that takes 4 vectors as arguments: x0,y0, x1,y1
npups <-length(pupil_data$PupilLeft)
segments(1:(npups-1), pupil_data$PupilLeft[-npups], # the starting points
2:npups, pupil_data$PupilLeft[-1] ) # the ending points

Resources