Reputation: 41
I'm trying to combine two functions with loops in R and create a plot with both Y vectors being plotted against a common X vector. I have been able to write and plot each function separately. I do not know how to combine the two functions and put them into one plot. Also, is there a way to export the resulting vectors so that I can use that data outside of the loop? My vectors "result" are not stored in the environment.
#Function #1:
k=1000
x=seq(from=1, to=k, by=1)
sumfun<-function(y){
sum<-0
result<-vector(mode="numeric")
for(i in 1:k) {
sum=sum+(1/i)
result[i]<-sum
}
plot(x,result, log="y",xlab="k",ylab="1, 1+1/2,..+1/k")
}
sumfun(x)
#Function #2
k=1000
x=seq(from=1, to=k, by=1)
sumfun<-function(y){
sum<-0
result<-vector(mode="numeric")
for(i in 1:k) {
sum=sum+(1/i)^2
result[i]<-sum
}
plot(x,result, log="y", xlab="k",ylab="1, 1+(1/2)^2,..+(1/k)^2")
}
sumfun(x)
Upvotes: 1
Views: 580
Reputation: 72683
To summarize, use the sapply
attempt from @bala83 to store your vectors in the environment.
y1 <- cumsum(sapply(1:k, function(i) 1/i)) # results from your 1st function
y2 <- cumsum(sapply(1:k, function(i) 1/i^2)) # results from 2nd
Then use points()
for the second plot as @John Coleman commented.
plot(y1, xlab="k",ylab="1, 1+(1/2)^2,..+(1/k)^2") # plots 1st
points(y2) # adds 2nd to the plot
Gives:
Case you want to draw lines and have a legend, do this
plot(y1, xlab="k",ylab="1, 1+(1/2)^2,..+(1/k)^2", type = "l")
points(y2, type = "l", col="red")
legend(720, 6.7,
c("Results 1","Results 2"),
lwd=c(1,1), cex=.8, col=c("black","red"))
Gives:
Upvotes: 1
Reputation: 443
Using apply is faster than looping. Also your results are in parent environment now.
library(ggplot2)
k=1000
y1 = cumsum(sapply(1:k, function(i) 1/i))
y2 = cumsum(sapply(1:k, function(i) 1/i**2))
df = data.frame("y"=c(y1,y2), "sum.type"=as.factor(rep(c("1","2"),each=k)))
ggplot(df,aes(c(1:k,1:k),log(y),color=sum.type)) + geom_point()+xlab("k")+ylab("Sum")+theme_classic()
Upvotes: 0
Reputation: 1939
You do not even need apply, there is a ready function for cumulative sums. I provide a solution plotting with ggplot library which is more popular than base R plotting
library(reshape2)
library(ggplot)
library(tidyverse)
k=1000
result1=cumsum(1/seq(from=1, to=k, by=1))
result2=cumsum(1/seq(from=1, to=k, by=1)^2)
x=1:k
df=tibble(x,result1,result2)%>%melt(measure.vars=c("result1","result2"))
ggplot(df)+geom_point(aes(x=x,y=value,col=variable))+ylab("1, 1+1/2,..+1/k")+xlab("k")
Upvotes: 1