《R语言初学指南》一2.4 利用注释使脚本明了

    xiaoxiao2024-05-09  8

    本节书摘来自异步社区《R语言初学指南》一书中的第2章,第2.4节,作者【美】Brian Dennis(布莱恩·丹尼斯),更多章节内容可以访问云栖社区“异步社区”公众号查看

    2.4 利用注释使脚本明了

    R语言初学指南可在脚本中加入注释。在脚本中,任何以“#”(sharp/number symbol)开头的命令行都会被R忽略。同样,若“#”出现在某行的中间,则该行中“#”后面的语句都会被忽略。可利用这一特性对脚本添加注释,以便用户或他人日后查阅。例如,作者每次查看前一天编写的脚本时,都要重新梳理并回忆每条脚本语句的作用。

    下面是添加注释之后,狼-驼鹿脚本可能呈现的样子:

    #================================================= # wolf moose graph version 20110625.R # R program to plot the average kill rate of moose per wolf # (average number of moose killed per wolf per 100 days; # vertical axis) with the density of moose (average number # per 1000 square km; horizontal axis), along with the model # equation for predation rate from ecological theory. # # Data are from Messier, F. 1994. Ungulate population models # with predation: a case study with the North American moose. # Ecology 75:478-488. #================================================= #--------------------------------------- # Enter data into two vectors. #--------------------------------------- moose.density=c(.17,.23,.23,.26,.37,.42,.66,.80,1.11,1.30,1.37,1.41, 1.73,2.49) kill.rate=c(.37,.47,1.90,2.04,1.12,1.74,2.78,1.85,1.88,1.96, 1.80,2.44, 2.81,3.75) #-------------------------------------- # Draw a scatterplot of the data. #-------------------------------------- plot(moose.density,kill.rate,type="p") #-------------------------------------- # Calculate predation rate equation over a range of moose # densities and store in two vectors, m and k. #-------------------------------------- m=2.5*(0:100)/100  # Range of moose densities from 0 to 2.5. a=3.37         # Prey density at which kill is half of             #  maximum. b=0.47         # Maximum kill rate. k=a*m/(b+m)      # Model equation calculated for all values          #  contained in the vector m. #-------------------------------------- # Plot the predation rate equation data as a line plot. #-------------------------------------- points(m,k,type="l")

    添加多少注释都不为过。尽管这需要输入更多的字符,但在将来这会节省很多脑力劳动。另外,用年-月-日的方法来记录日期(参见第一行注释中“version 20110625”),可产生一系列连续增加的数字,这对分类、存储、查找及提取文件都很有用。

    注释对脚本调试很有用。只要在每个不需要运行的命令行前面添加“#”号,即可通过“注释”使脚本在运行时忽略其中的一行或一部分。将一部分脚本改为注释,然后通过运行另外的一条或一组语句来进行调试,这样可以保留原来的输入。

    相关资源:敏捷开发V1.0.pptx
    最新回复(0)