tips for R


  1. read.table读取数据多出一列NA值


  2. 怎样来计算函数运行使用时间?


  3. Why doesn’t R think these numbers are equal?

    The only numbers that can be represented exactly in R’s numeric type are integers and fractions whose denominator is a power of 2. Other numbers have to be rounded to (typically) 53 binary digits accuracy. As a result, two floating point numbers will not reliably be equal unless they have been computed by the same algorithm, and not always even then. For example

      R> a <- sqrt(2)
      R> a * a == 2
      [1] FALSE
      R> a * a - 2
      [1] 4.440892e-16

    The function all.equal() compares two objects using a numeric tolerance of .Machine$double.eps ^ 0.5. If you want much greater accuracy than this you will need to consider error propagation carefully.

    For more information, see e.g. David Goldberg (1991), “What Every Computer Scientist Should Know About Floating-Point Arithmetic”, ACM Computing Surveys, 23/1, 5–48, also available via

  4. 可以通过Sys.getenv()和Sys.setenv()设置当前R的shell环境变量。

  5. 编写R包的时候, 可以通过在src目录下放置Makevars文件指定特殊的编译选项,比如需要GCC的C++11选项

  6. reshape2包里面cast函数的公式写法形为不变列+...~因子转变量列+...,被转换的value列不会出现在公式中。如data.frame(a,b,c,d)通过公式a+b~c不改变ab列的情形下将c列的不同元素转换到列上,并以d列数据填充这些新列。

  7. 运用identify/locator读取figure中数据点位置可实现交互式绘图。

  8. R官方在Windows和Mac OS X系统中提供了已编译好的二进制包,在install.packages()中指定参数type='mac.binary.mavericks'等即可。

  9. 采用函数get(可以获取当前环境下var.name这一名称变量指定对象。这在data.table等包里是有用的。例如, <- "A", dt <- dt[,B:=get(]可以实现获取dt中的”A”这一列的功能。

  10. 采用x <- factor(x,levels(x)[new_order])可以方便地重新排序已经是因子型的变量x.