[英]R split() function size increase issue
我有以下数据集
> head(data)
X UserID NPS V3 V4 V5 Event V7 Element ElementValue
1 1 254727216 10 0 19 10 nps.agent.14b.no other attempt was made 10/4/2014 23:59 cea.element_name nps.agent.14b.no other attempt was made
2 2 298379949 0 0 28 11 nps.agent.14b.no other attempt was made 9/30/2014 23:59 cea.element_name nps.agent.14b.no other attempt was made
3 3 254710917 0 0 20 12 nps.agent.14b.no other attempt was made 9/15/2014 23:59 cea.element_name nps.agent.14b.no other attempt was made
4 4 238919392 7 0 17 9 nps.agent.14b.no other attempt was made 9/17/2014 23:59 cea.element_name nps.agent.14b.no other attempt was made
5 5 144693025 10 0 18 10 nps.agent.14b.no other attempt was made 9/17/2014 23:59 cea.element_name nps.agent.14b.no other attempt was made
6 6 249978568 5 0 21 12 nps.agent.14b.no other attempt was made 9/18/2014 23:59 cea.element_name nps.agent.14b.no other attempt was made
当我将数据集拆分为:
data_splitted <- split(data,data$UserID)
这里的问题是大小的巨大增加,当我使用整个数据集而不是此示例尝试时,大小超出了我的内存
> format(object.size(data),units="Mb")
[1] "0.2 Mb"
> format(object.size(data_splitted),units="Mb")
[1] "45.7 Mb"
对于为什么会这样以及是否有解决这个问题的任何见解,我们将不胜感激。
尝试这个:
data$UserID <- as.character(data$UserID)
data_splitted <- split(data,data$UserID)
您遇到的情况是,由于ID是数字,所以该数字被用作创建列表中的索引(位置),这显然是不正确的。 由于id的数量很高,因此R用尽可能多的空列表填充了空白(因此,对象大小很大)。 通过将id设置为字符变量,可以避免这种情况。
将id变量完整保留在1行数据框中的另一种方法是:
data_splitted <- list()
for(i in 1:nrow(data))
data_splitted[[as.character(data$UserID[i])]] <- data[i,]
要访问新创建的列表中的元素 ,如果使用$
运算符,则需要引用数字:
data_splitted$"144693025"
data_splitter[["144693025"]]
另一种选择是在数字id之前添加字符。 例如:
data$UserID <- paste0("id",data$UserID)
data_splitted <- split(data,data$UserID)
这使得访问列表项更加方便:
data_splitted$id144693025
data_splitted$id238919392
如果您有很多相似的字符串,请使用因子而不是字符串。 (并且,如果您不需要处理它们的内容,则根本不存储它们,或者仅存储例如主机名,再次作为因素。您可以将grep
与正则表达式一起使用,并且仅将捕获字段用于例如主机名和错误-代码,然后丢弃其他所有内容)。
接下来,通过更改或对日志文件进行以下处理,使分割工作变得轻松:
nps.agent.14b.no other attempt was made
至:
nps.agent.14b:no other attempt was made
现在,您只需对':'(或'|')进行拆分,看看一些日志文件的最佳实践,上面写了很多好东西。 如果保证每一行只有一个主机名和一个错误代码,则可以将它们存储为单独的主机名和ErrorCode字段。
因此,您的代码应该很简单:
> as.factor(strsplit(s, ':')
[1] 'nps.agent.14b' 'no other attempt was made'
同样,如果您不需要处理“没有其他尝试”,则不要存储它。 否则您的日志文件消息可能会将其压缩为“ NEA”。 或者,如果它无法传达任何额外信息,则将其丢弃。
我建议您重新访问日志文件格式,并尽量使其简洁明了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.