2009-11-25 99 views
3

我使用R循环遍历数据框的列并生成分析结果图。脚本运行时,我不会收到任何错误,但会生成无法打开的pdf。使用R中的脚本生成pdf时出错使用R中的脚本

如果我运行脚本的内容,它工作正常。我想知道是否有一个问题,它循环的速度有多快,所以我试图强迫它暂停。这似乎没有什么区别。我对任何人的建议都很感兴趣,而且我对R也很陌生,所以我建议如何改进这种方法也值得欢迎。谢谢。

for (i in 2:22) { 

    # Organise data 
    pop_den_z = subset(pop_den, pop_den[i] != "0") # Remove zeros 
    y = pop_den_z[,i]  # Get y col 
    x = pop_den_z[,1]  # get x col 
    y = log(y)    # Log transform 

    # Regression 
    lm.0 = lm(formula = y ~ x)    # make linear model 
    inter = summary(lm.0)$coefficients[1,1] # Get intercept 
    slop = summary(lm.0)$coefficients[2,1] # Get slope 

    # Write to File 
    a = c(i, inter, slop) 
    write(a, file = "C:/pop_den_coef.txt", ncolumns = 3, append = TRUE, sep = ",") 

    ## Setup pdf 
    string = paste("C:/LEED/results/Images/R_graphs/Pop_den", paste(i-2), "City.pdf") 
    pdf(string, height = 6, width = 9) 

    p <- qplot(
    x, y, 
    xlab = "Radius [km]", 
    ylab = "Population Density [log(people/km)]", 
    xlim = x_range, 
    main = "Analysis of Cities" 
) 

    # geom_abline(intercept,slope) 
    p + geom_abline(intercept = inter, slope = slop, colour = "red", size = 1) 

    Sys.sleep(5) 

    ### close the PDF file 
    dev.off() 
} 

回答

10

该行应该是

print(p + geom_abline(intercept = inter, slope = slop, colour = "red", size = 1)) 

在PDF设备,ggplot(和晶格)只写明确地打印时到文件。

+0

这只是格和ggplot2,并没有真正与网格有关。 – hadley 2009-11-25 17:44:38

+0

谢谢哈德利。修复。 – 2009-11-25 19:04:46

+0

谢谢你,工作。我没有意识到它需要明确打印。 – womble 2009-11-25 19:19:29