对于初学者:我现在在这个问题上搜索了几个小时 - 所以如果答案应该是微不足道的,请原谅我......
我想要做的是从data.frame中删除一行(编号101).它包含测试数据,不应出现在我的分析中.我的问题是:每当我从data.frame中进行子集化时,属性(特别是注释)都会丢失.
str(x)
# x has comments for each variable
x <- x[1:100,]
str(x)
# now x has lost all comments
Run Code Online (Sandbox Code Playgroud)
有充分证据表明,子集将丢弃所有属性 - 到目前为止,它非常清楚.手册(例如http://stat.ethz.ch/R-manual/R-devel/library/base/html/Extract.data.frame.html)甚至建议了一种保留属性的方法:
## keeping special attributes: use a class with a
## "as.data.frame" and "[" method:
as.data.frame.avector <- as.data.frame.vector
`[.avector` <- function(x,i,...) {
r <- NextMethod("[")
mostattributes(r) <- attributes(x)
r
}
d <- data.frame(i= 0:7, f= gl(2,4),
u= structure(11:18, unit = "kg", class="avector"))
str(d[2:4, -1]) # 'u' keeps its "unit"
Run Code Online (Sandbox Code Playgroud)
到目前为止,我还不知道究竟发生了什么.但是,只需运行这些行(除了最后三行)不会改变我的子集的行为.使用带有适当向量的命令subset()(100次TRUE + 1 FALSE)给出了相同的结果.简单地将属性存储到变量并在子集之后恢复它也不起作用. …
我make
总是重建Makefile
目标(make 总是重建 Makefile 目标)的问题及其调查发现了另一个问题,这是这个问题的主题。重复执行以下R
代码导致对象属性丢失数据转换操作期间。
为了记录,我不得不说我已经写过这个主题(在提取/替换操作期间保留对象属性的方法),但是这个问题和答案更笼统(我不正确,简单的保存属性是有效的 - 它在撰写本文时为我工作,因为当时我还没有执行操作,这对对象的属性有潜在危险)。
以下是我的 R 代码的摘录,其中我遇到了属性丢失的问题。
##### GENERIC TRANSFORMATION FUNCTION #####
transformResult <- function (dataSource, indicator, handler) {
fileDigest <- base64(indicator)
rdataFile <- paste0(CACHE_DIR, "/", dataSource, "/",
fileDigest, RDS_EXT)
if (file.exists(rdataFile)) {
data <- readRDS(rdataFile)
# Preserve user-defined attributes for data frame's columns
# via defining new class 'avector' (see code below)). Also,
# preserve attributes (comments) for the data …
Run Code Online (Sandbox Code Playgroud)