【问题标题】:Combine and plot multiple functions with loops in R在 R 中使用循环组合和绘制多个函数
【发布时间】:2018-09-03 00:32:20
【问题描述】:

我正在尝试将两个函数与 R 中的循环结合起来,并创建一个图,其中两个 Y 向量都被绘制在一个公共 X 向量上。 我已经能够分别编写和绘制每个函数。 我不知道如何将这两个功能结合起来并将它们放在一个情节中。另外,有没有办法导出结果向量,以便我可以在循环之外使用该数据?我的向量“结果”没有存储在环境中。

#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)

【问题讨论】:

  • 函数points() 可以像plot() 一样使用,但它会为现有绘图添加点。评估 ?points 以查看帮助文件。

标签: r function loops plot


【解决方案1】:

总而言之,使用@bala83 中的sapply 尝试将您的向量存储在环境中。

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

然后使用points() @John Coleman 评论的第二个情节。

plot(y1, xlab="k",ylab="1, 1+(1/2)^2,..+(1/k)^2")  # plots 1st
points(y2)  # adds 2nd to the plot

给予:

如果您想画线并有图例,请执行此操作

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"))  

给予:

【讨论】:

  • ggplot 可能更可取,但 OP 仍然应该知道 points() +1
【解决方案2】:

使用 apply 比循环更快。您的结果现在也在父环境中。

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()

这是我得到的:

【讨论】:

  • 使用 sapply 我收到一个错误,即 x 和 y 的长度不同。
  • @kxb35 是的,对不起,我做了 sum 而不是 cumsum 哈哈!现在它应该可以工作了:)
  • 我不熟悉 ggplot 也不知道如何处理这个错误 "Error in aes(1:k, log(y, color = ~sum.type)) + xlab( "k") : 二元运算符的非数字参数"
  • 看起来数据框是 2000 行而不是 1000 (k)。
  • @kxb35 是的,我应该在添加答案之前测试我的代码哈哈!对不起,伙计!
【解决方案3】:

你甚至不需要申请,有一个累积和的现成函数。我提供了一个使用 ggplot 库进行绘图的解决方案,它比基本 R 绘图更受欢迎

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")

【讨论】:

    猜你喜欢
    • 2017-07-31
    • 2022-01-05
    • 2021-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-14
    • 2014-01-20
    • 1970-01-01
    相关资源
    最近更新 更多