如何在R中循环或缩短此脚本

时间:2016-09-28 15:59:11

标签: r plot

我需要绘制这些图中的大约50个,我只需要更改x,y和数据。有没有办法缩短这个让它看起来不那么混乱?无需下载任何外部库。

RatingsA,RatingsB和Looks是具有大约100k值的向量,例如(“Null”,439 ......等)

#Plotting graphs based based on Looks Vs Ratings
png('1.png')
par(mfrow=c(4,2))
plot(RatingA ~ Age, main="Looks Vs RatingA at List1", xlab="Looks",     ylab="RatingA", xlim=c(20,80), data=List1)
plot(RatingA ~ Age, main="Looks Vs RatingA at List2", xlab="Looks", ylab="RatingA", xlim=c(20,80), data=List2)
plot(RatingA ~ Age, main="Looks Vs RatingA at List3", xlab="Looks", ylab="RatingA", xlim=c(20,80), data=List3)
plot(RatingA ~ Age, main="Looks Vs RatingA at List4", xlab="Looks", ylab="RatingA", xlim=c(20,80), data=List4)
plot(RatingA ~ Age, main="Looks Vs RatingA total", xlab="Looks", ylab="RatingA", xlim=c(20,80), data=mainlist)
dev.off()

png('2.png')
par(mfrow=c(4,2))
plot(RatingB ~ Looks, main="Looks Vs RatingB at EVR1", xlab="Looks", ylab="RatingB", xlim=c(20,80), data=List1)
plot(RatingB ~ Looks, main="Looks Vs RatingB at EVR2", xlab="Looks", ylab="RatingB", xlim=c(20,80), data=List2)
plot(RatingB ~ Looks, main="Looks Vs RatingB at EVR3", xlab="Looks", ylab="RatingB", xlim=c(20,80), data=List3)
plot(RatingB ~ Looks, main="Looks Vs RatingB at EVR4", xlab="Looks", ylab="RatingB", xlim=c(20,80), data=List4)
plot(RatingB ~ Looks, main="Looks Vs RatingB total", xlab="Looks", ylab="RatingB", xlim=c(20,80), data=mainlist)
dev.off()

2 个答案:

答案 0 :(得分:1)

将它们放入功能。参数是您想要更改的变量,即xydata

plot_graph <- function(x, y, data)
{
        your code here, you need to change the original code a little bit, 
    by putting x, y, data instead of specific values.
}

每当你想绘制图表时,只需调用函数:

plot_graph(x_value, y_value, your_data)

现在,它更清楚了。

然后,您可以使用for循环或apply函数(或某种函数可以映射,我的意思是它可以将数据拆分成多个部分,然后将功能应用于每个部分。)

for循环示例:

#vector x_vector store 50 values for x
x_vector = c(x1_value, x2_value,   ,x50_value)

#do the same with y_vector, data
y_vector = c(y1_value, y2_value,   ,y50_value)
data= c(data1, data2,   ,data50)

#plot 50 graghs
for (i in 1:50)
    plot_graph(x_vector[i], y_vector[i], data[i])

您还可以使用apply功能(函数式编程)。它比循环更好,但有点复杂。

答案 1 :(得分:0)

在函数中概括您的绘图代码。我认为你的问题中有一个拼写错误,第一组情节的标题可能应该是“年龄与评级A”。如果你真的想要带有数字的情节标题,请在函数中添加另一个参数,并在png中使用它。稍后将其作为第三个参数输入map

func_plot = function(x, y) {
  png(paste0(x, ".png"))
  par(mfrow=c(4,2))
  f = as.formula(y~x)
  plot(f, main=paste0(x, " Vs ", y, " at EVR1"), xlab=x, ylab=y, xlim=c(20,80), data=List1)
  plot(f, main=paste0(x, " Vs ", y, " at EVR2"), xlab=x, ylab=y, xlim=c(20,80), data=List2)
  plot(f, main=paste0(x, " Vs ", y, " at EVR3"), xlab=x, ylab=y, xlim=c(20,80), data=List3)
  plot(f, main=paste0(x, " Vs ", y, " at EVR4"), xlab=x, ylab=y, xlim=c(20,80), data=List4)
  plot(f, main=paste0(x, " Vs ", y, " Total"), xlab=x, ylab=y, xlim=c(20,80), data=mainlist)
  dev.off()
}

运行要迭代的事物列表的函数。

Map(func_plot, c("RatingA", "RatingB", etc), c("Age", "Looks", etc))