R嵌套循环写入多个函数并绘制它们 [英] R nested for loop to write multiple functions and plot them

查看:138
本文介绍了R嵌套循环写入多个函数并绘制它们的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的资料:

  color ab 
red 3 1.3
blue 9 1.8
紫色13 1.2
绿色4 1.1
橙色7 0.9
黄色6 2.1
褐色7 1.8

对于每一行,我想用下面的格式写一个名为fun_color的函数: y = a *(x ^ b) $ a





$函数。)



我假设我应该为以下内容编写一个嵌套for循环:

<$ p $($($))$ b $ {$ paste $$ {code $ dt $ a)
{a * x}
}

然而, ,一个相对R新手,不能完全得到这个循环工作。

然后,我想在同一个图上绘制这10个方程的每一个。我假设我应该在这里写另一个for循环,例如:
$ b $ pre $ code $ ){
plot(i,add = TRUE)}

谢谢!

解决方案

选择一个 x 他们与sapply。无需多次调用绘图函数,只需使用 matplot 即可。
$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ sapply(s,function(x)dt $ a *(x)^ dt $ b)),
type =l,lty =solid,lwd = 2,col = dt $ color,ylab = y,xlab =x)


Here is my data:

color   a   b
red     3   1.3
blue    9   1.8
purple  13  1.2
green   4   1.1
orange  7   0.9
yellow  6   2.1
brown   7   1.8

For each row, I'd like to write a function called "fun_color" by the following format: y = a*(x^b)

(a and b are the values of the data$a and data$b column for each row. x is the domain of the function.)

I assumed I should write a nested for loop along the following:

for (i in dt$color) 
  {(paste("fun_",i, sep = "")) = function(x)
    for (a in dt$a) 
      {a*x}
    }

However, I, a relative R newbie, can't quite get this for loop to work.

I'd then like to plot each of these 10 equations on the same plot. I assume I should write another for loop here, something like:

plot(fun_red)
for (i in function_list) {
  plot(i, add=TRUE)}

Any help? Thanks!

解决方案

Choose a sequence of x values, and iterate over them with sapply. No need to call the plotting functions many times, just use matplot.

s <- seq(.2,5,by =.2)
matplot(s,t(sapply(s, function(x) dt$a*(x)^dt$b)),
        type = "l", lty = "solid", lwd = 2, col = dt$color, ylab = "y", xlab = "x")

这篇关于R嵌套循环写入多个函数并绘制它们的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆