R语言数据类型 1:Names and values
1.安装
We’ll use the lobstr package to dig into the internal representation of R objects.
install.packages("lobstr")
library(lobstr)
2. Non-syntactic names 非语法名称
- A syntactic name must consist of letters, digits, . and _ but can’t begin with _ or a digit.
- Additionally, you can’t use any of the reserved words like TRUE, NULL, if, and function.
if else repeat while function for in next break TRUE FALSE NULL Inf NaN NA NA_integer_ NA_real_ NA_complex_ NA_character_
如何创建一个符合语法规则的名称?在R中,有效的名称可以包含字母、数字、“.”、和“_”,并以字母或点开头(点后不能直接跟数字),但是不能以_或数字开头。
- 生成语法有效的名称
make.names(names, unique = FALSE, allow_ = TRUE)
- The character “X” is prepended if necessary.
- All invalid characters are translated to “.”.
- A missing value is translated to “NA”. Names which match R keywords have a dot appended to them.
- Duplicated values are altered by make.unique.
make.names(c("a and b", "a-and-b"), unique = TRUE)
3.Copy-on-modify 修改时复制
x <- c(1, 2, 3)
y <- x
y[[3]] <- 4
x
在对y进行修改时,并没有改变x。这说明,在修改y时创建了一个新的对象,然后将y重新绑定到这个对象。
- base::tracemem():对象的跟踪复制
tracemem(x)#对象的跟踪复制
untracemem(x)
retracemem(x, previous = NULL)
4.Object size 对象大小
- lobstr::obj_size()查看一个对象占用了多少内存
obj_size(..., env = parent.frame()) # 计算一个对象或一组对象的大小
obj_sizes(..., env = parent.frame()) #分析多个对象对总大小的单独贡献
5.Modify-in-place 原地修改
- Two exceptions:
- Objects with a single binding get a special performance optimisation.
- Environments, a special type of object, are always modified in place.
to be continued
6.Unbinding and the garbage collector 解绑和垃圾回收器
x <- 1:3
x <- 2:4
rm(x)
运行以上代码后,此时有两个对象,分别是c(1,2,3)和c(2,3,4),但这两个对象没有绑定到任何名称。
如何删除这两个对象?
- GC 通过删除不再使用的 R 对象来释放内存,并在需要时向操作系统请求更多内存
gc(verbose = getOption("verbose"), reset = FALSE, full = TRUE)
gcinfo(verbose)
- 调用 gc 会导致进行垃圾收集。这也会在无需用户干预的情况下自动进行,调用 gc 的主要目的是报告内存使用情况。为了获得准确的报告,应使用 full = TRUE。
- 在删除一个大型对象后调用 gc 可能很有用,因为这可能会促使 R 将内存返回给操作系统。