Coding a plot with functions [closed] - r

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
So I've probably referenced the entire internet trying to make this problem work, and haven't. However, I found stack overflow. Like I said I've been learning for not even 2 weeks yet.
So this is the problem
Let
f(x)=sqrt((x^3+3x^2+1)/(x^4+5x^3+7x+9))
(x ≥ 0)
(a) Draw a line graph of (x, f(x)) for 0 ≤ x ≤ 10 with increments of 0.01
(b) Find numerically the maximum value of f(x) and the maximizer x (report x to the
second decimal place. For instance, x = 1.23)
So I'm basically been saying x=x and y= the sqrt....., and then I write plot(x,y,type="l") and usually it just doesn't even work.
Also how do I do the increment part. I'm sorry for lack of explanation, but I have no idea what most of this means.

First thing to do would be to define the function:
equation <- function(x){
sqrt((x^3+3*x^2+1)/(x^4+5*x^3+7*x+9))
}
Then, define the values you want to apply the function to, and store them in vector input
input<-seq(0,10,0.01)
Apply the equation function to input, and store the values in vector results
results<-sapply(input,function)
Produce a line plot:
plot(input,results,type="l")
Print the value of x which maximises f(x)
maxx<-input[which.max(results)]
maxx

I would suggest a ggplot2 approach. First you have to create a random x variable and then compute y. I will add the code for that variables an the plot.
In the case of finding the maximum of f(x) you must know calculus or you can use a visual approach. Here the code:
library(ggplot2)
library(dplyr)
set.seed(123)
First we create a random variable x with the limits you mentioned:
#Data
x <- runif(100,0,10)
Now, we save the variable in a dataframe and compute y:
#Allocate data in a dataframe
df <- data.frame(x=x)
#Compute variable
df$y <- sqrt(((df$x^3)+3*((df$x)^2)+1)/((df$x^4)+5*(df$x)^3+7*(df$x)+9))
Finally, we plot:
#Plot
ggplot(df,aes(x=x,y=y))+
geom_point()+
scale_x_continuous(limits = c(0,10))
Output:
Values for x are randomly generated, if you have real values for x you should use those values.

Related

Function to Create Y-Values

I was hoping someone might be able to help me make sense of a homework question. I am not looking for a solution, mind you, just wondering if anyone would be able to explain the question a bit more simply for me, as I am new to data analysis and enrolled in an R class which had no prerequisites, but feel a bit lost with some of the language. Any help would be greatly appreciated!
So, the first part of the question was to create an array and fill it with random numeric data, which I did here:
question <- array( 1:1000, dim= c(25,4,1000))
colnames(question)<- c('x1','x2','x3','x4')
Now, the second part asks me to "write a function to create y-values," which should be a "linear combination" of the four variables. The example given is
y = 2 ∗ x1 + 5 ∗ x2 − 3 ∗ x3 + 0.7 ∗ x4 + RandomError.
The question adds that the result should be a matrix with dimensions of 25 × 1000. I am not sure what exactly this is asking or how to approach this problem. All I have so far, which I know is very little is
apply(question,c(1,3),sum)
function (y){ ...
Can anyone offer any guidance or clarification? Thank you so much!
First of all, to make (pseudo)random numbers, you can use the rnorm function. That is, if you want to make 1000 random numbers that are normally distributed with mean of 0 and sd of 1, you can do rnorm(1000) (However, your array ends up being length 10000, so maybe you actually want to do rnorm(10000)).
Now, you should have an array question with dimensions 25 x 4 x 1000. You want to create a matrix y which combines four "slices" in question of size 25 x 1000 to create a matrix y of size 25 x 1000. You want to write a function f that will take all four "slices" of array question and combine them into one slice. You also want to incorporate random error, which again can be accomplished with the rnorm function.
For a simple example, let's make an array x with dimensions(10,2,10)
x = array(rnorm(200), dim = c(10,2,10))
And now let's write a function f that will add the two "slices" of x together.
f = function(my_array){
my_array[,1,] + my_array[,2,]
}
Let's execute the function on our array
y = f(x)
dim(y)
Hopefully you can expand this basic example to fit your case.

plotting 3d graph by stacking 2d contour plots in R [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 7 years ago.
Improve this question
I have got two different variables x and y that are both functions of variable z. I have multiple contour plots of x vs y at different z values. What I want to do is put these graph slices together along z axis to get a 3D-ish graph.
I searched for packages that lets me do this in R and all I could find was contourrslice in Matlab. Contourslice is exactly what I want but in R.
Is there a package/ function in R like contourslice or any other ways I could go about doing this?
EDIT: Here's a dummy data. For different values of z the heat map changes. I have these several 2D plots, for values of z from -1 to 15. I want to put these 2D plots together along z axis to get a 3D ish figure to see how the red area is displaced.
#Create range of values for x and y
x<- c(11,25)
y<- c(1,5)
length<-10
x_ran <- as.matrix(seq(x[1],x[2], len=length))
y_ran <- as.matrix(seq(y[1],y[2], len=length))
#initialise matrix
x_mat<- x_ran[,rep(1,length)]
y_mat<- t(y_ran[,rep(1,length)])
#Third variable z
z<- -1
#z<- 1
#z<-2
#z<-3
#R and C, funcition of z
R <- x_mat*z
C<-z-y_mat
toget<- R/C
image(toget, xlab="R", ylab="C")

Dataset with NaN values for a filled contour plot with R [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I cannot get my data plotted properly with R. I got measurements from a football field and I did not fill measurements for each grid.
Here is my dataset contour_map_R.csv at https://db.tt/1L7cxilB
It looks like this using image function to plot it.
Any one can provide an example to create a filled contour plot?
Thanks a lot!
As stated in the comments you need to have complete data before you can calculate contours. Therefore you have to interpolate or replace your missing values in some way that makes sense in your case. I've provided a couple of options below, but you'd need to come up with rationale for using one method over another, and whether a more sophisticated geostatistical approach might be warranted. Furthermore you could interpolate to a finer grid than you currently have as well to produce a smoother result (at the expense of potentially making up data).
d <- read.csv("contour_map_R.csv")
library(raster)
r <- raster(as.matrix(d))
contour(r)
v <- getValues(r)
xy <- xyFromCell(r, 1:ncell(r))
## Interpolate using a thin-plate spline:
library(fields)
tps <- Tps(xy, v)
tp <- interpolate(r, tps)
plot(tp)
contour(tp, add=T)
## Alternatively, interpolate using nearest idw():
library(gstat)
dxy <- data.frame(x=xy[,1], y=xy[,2], v)
dxy <- dxy[complete.cases(dxy),]
id <- gstat(formula = v~1, locations = ~x+y, data=dxy)
ip <- interpolate(r, id)
plot(ip)
contour(ip, nlevels=5, add=T)
If that's what you were looking for you can get filled contours by using the filledContour() function on the interpolated rasters (tp or ip).

Logical Venn Diagrams [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
I have this question :
Unfortunately, my book didn't provide definition and how to draw/read a logic venn diagram, i have to look at the internet but couldn't find any understandable explanation
From what i understand, the logics for the three diagrams are :
X AND NOT (Y OR Z)
NOT X AND (Y OR Z)
Y AND NOT (X OR Z)
Am i right ? Please correct me if i'm wrong
By the ways, does the question mean to combine all three diagrams with OR operation, like :
1 OR 2 OR 3
Any help is greatly appreciated !
I could not understand the question correctly. Here's the logic for the three Venn Diagrams:
1. Your logic for the first Venn Diagram is correct: X AND NOT (Y OR Z)
2. Your logic for the second Venn Diagram is slightly incorrect, if you look at the Venn Diagram: It is simply NOT (X) (Everything except X).
3. In this case as well, the logic is simply Y.
Now if we perform OR operation on these three:
(X AND NOT (Y OR Z)) + NOT(X) + Y
= X AND NOT(Y) AND NOT(Z) OR NOT(X) OR Y [By de Morgan's law]
which matches option c.
NOTE: Your second and third logics would have been correct if X, Y and Z were the only three regions in the diagram. However there is also a region outside all of them - bounded by the box. You might want to look up on the internet about basics of Venn Diagram, it's one of the easiest things to learn IMO!

Detecting cycle maxima (peaks) in noisy time series (In R?) [closed]

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 9 years ago.
Improve this question
This question is about an algorithm for determining the number and location of maxima in a sequence of numbers. Thus, there is a statistical flavor to the question, but it is more leaning towards programming, because I am not interested in the specific statistical properties, and the solution needs to be in R. The use of statistics to answer this question is OK, but not a requirement.
I want to extract maxima of cycles in time series data (i.e., an ordered sequence of numbers). An example of such data is the solar flare time series (~11 year cycle, between 9 & 14 years). The cycles don't repeat at a perfect interval, and the peaks aren't always the same height.
I found a recent paper describing an algorithm for this, and the paper actually uses solar flares as an example (Figure 5, Scholkmann et al. 2012, Algorithms). I was hoping that this algorithm, or an equally effective algorithm, was available as an R package.
Link to Scholkmann paper on "automatic multiscale-based peak detection"
http://www.mdpi.com/1999-4893/5/4/588
I've tried the "turningpoints" function in the "pastecs" package but it seemed to be too sensitive (i.e., detected too many peaks). I thought of trying to smooth the time series first, but I'm not sure if this is the best approach (I'm no expert).
Thanks for any pointers.
If the peaks are almost periodic (with a slowly fluctuating period), as in the sunspot example,
you can use the Hilbert transform or the empirical mode decomposition to smooth the time series.
library(EMD)
x <- as.vector(sunspots)
r <- emd(x)
# Keep 5 components -- you may need more, or less.
y <- apply( r$imf[,5:10], 1, sum ) + mean(r$residue)
plot(x, type="l", col="grey")
lines( y, type="l", lwd=2)
n <- length(y)
i <- y[2:(n-1)] > y[1:(n-2)] & y[2:(n-1)] > y[3:n]
points( which(i), y[i], pch=15 )
Here is a solution involving the wmtsa package in R. I added my own little function to facilitate the searching of maxima once the wmtsa::wavCWTPeaks got it close.
PeakCycle <- function(Data=as.vector(sunspots), SearchFrac=0.02){
# using package "wmtsa"
#the SearchFrac parameter just controls how much to look to either side
#of wavCWTPeaks()'s estimated maxima for a bigger value
#see dRange
Wave <- wavCWT(Data)
WaveTree <- wavCWTTree(Wave)
WavePeaks <- wavCWTPeaks(WaveTree, snr.min=5)
WavePeaks_Times <- attr(WavePeaks, which="peaks")[,"iendtime"]
NewPeakTimes <- c()
dRange <- round(SearchFrac*length(Data))
for(i in 1:length(WavePeaks_Times)){
NewRange <- max(c(WavePeaks_Times[i]-dRange, 1)):min(c(WavePeaks_Times[i]+dRange, length(Data)))
NewPeakTimes[i] <- which.max(Data[NewRange])+NewRange[1]-1
}
return(matrix(c(NewPeakTimes, Data[NewPeakTimes]), ncol=2, dimnames=list(NULL, c("PeakIndices", "Peaks"))))
}
dev.new(width=6, height=4)
par(mar=c(4,4,0.5,0.5))
plot(seq_along(as.vector(sunspots)), as.vector(sunspots), type="l")
Sunspot_Ext <- PeakCycle()
points(Sunspot_Ext, col="blue", pch=20)

Resources