美文网首页
R之L到底是什么鬼

R之L到底是什么鬼

作者: 见龙在田007er2770 | 来源:发表于2019-07-10 20:31 被阅读0次

Q:I often seen the symbol 1L (or 2L, 3L, etc) appear in R code. Whats the difference between 1L and 1? 1==1L evaluates to TRUE. Why is 1L used in R code?

A:Most of the time it makes no difference - but sometimes you can use it to get your code to run faster and consume less memory. A double ("numeric") vector uses 8 bytes per element. An integer vector uses only 4 bytes per element. For large vectors, that's less wasted memory and less to wade through for the CPU (so it's typically faster).

Mostly this applies when working with indices. Here's an example where adding 1 to an integer vector turns it into a double vector:

x <- 1:100
typeof(x) # integer
object.size(y) # 448 bytes (on win64) 
y <- x+1
typeof(y) # double
object.size(y) # 848 bytes (on win64) 
z <- x+1L
typeof(z) #  integer
object.size(z) # 448 bytes (on win64) 
...but also note that working excessively with integers can be dangerous:
1e9L * 2L # Works fine; fast lean and mean!
1e9L * 4L # Ooops, overflow!

链接

原始文档

From the Constants Section of the R Language Definition:

We can use the ‘L’ suffix to qualify any number with the intent of making it an explicit integer. So ‘0x10L’ creates the integer value 16 from the hexadecimal representation. The constant 1e3L gives 1000 as an integer rather than a numeric value and is equivalent to 1000L. (Note that the ‘L’ is treated as qualifying the term 1e3 and not the 3.) If we qualify a value with ‘L’ that is not an integer value, e.g. 1e-3L, we get a warning and the numeric value is created. A warning is also created if there is an unnecessary decimal point in the number, e.g. 1.L.

相关文章

网友评论

      本文标题:R之L到底是什么鬼

      本文链接:https://www.haomeiwen.com/subject/zopkkctx.html