【发布时间】:2017-06-06 10:25:54
【问题描述】:
我拥有包含数百万条记录的海量数据。我只是分享它的一部分。
data<-structure(list(email_address_hash = structure(c(1L, 1L, 2L, 2L,
2L, 3L, 3L), .Label = c("0004eca7b8bed22aaf4b320ad602505fe9fa9d26",
"00198ee5364d73796e0e352f1d2576f8e8fa99db", "35c0ef2c2a804b44564fd4278a01ed25afd887f8"
), class = "factor"), open_time = structure(c(1L, 5L, 7L, 3L,
2L, 4L, 6L), .Label = c(" 04:39:24", " 06:31:24", " 07:05:23",
" 09:57:20", " 10:39:43", " 19:00:09", " 21:12:04"), class = "factor")), .Names = c("email_address_hash",
"open_time"), row.names = c(NA, -7L), class = c(
"data.frame"))
require(data.table)
setDT(data)
这就是我的数据的样子
我想把每个 email_address_hash 的 open_times 以向量的形式放在它前面。我尝试了以下方法
data <- data[, .(open_times = paste(open_time, collapse = "")), by = email_address_hash]
str(data)
Classes ‘data.table’ and 'data.frame': 3 obs. of 2 variables:
$ email_address_hash: Factor w/ 36231 levels "00012aec4ca3fa6f2f96cf97fc2a3440eacad30e",..: 2 16 7632
$ open_times : chr " 04:39:24 10:39:43" " 21:12:04 07:05:23 06:31:24" " 09:57:20 19:00:09"
- attr(*, ".internal.selfref")=<externalptr>
有两件事我想解决
1) 首先想从 open_times 中删除前导空格
2) 我想分别处理 email_address_hash 前面的每个 open_times 。见下文 open_times 的元素被连接成一个元素。
电流输出
data$open_times[1]
[1] " 04:39:24 10:39:43"
NROW(data$open_times[1])
[1] 1
期望的输出
data$open_times[1]
[1]"04:39:24" "10:39:43"
NROW(data$open_times[1])
[1] 2
对于单个元素,我可以这样做
unlist(strsplit(trimws(data$open_times[1]),split = " "))
但是由于我的数据很大,我想避免 for 循环,因为迭代所有这些东西需要花费很多时间。谁能为我提供一个在大数据上更快的解决方案?数百万甚至数十亿的记录。使用 data.table 的解决方案更可观
如果您有任何不清楚的地方,请告诉我。
【问题讨论】:
-
试试
data[,list(open_time=list(open_time)),by=email_address_hash]。 -
有趣。为问得好问题点赞。如果您有很多进一步的分析要做,我只会考虑大数据框架。如果只是格式化,那么它必须在 R 中完成吗?如果我有计算密集型格式,我想在 RI 中使用louisaslett.com/RStudio_AMI(2-3 分钟)设置一个 EC2 实例并让它在一夜之间运行,在你的情况下,R Server 可以使用 sapply() 解决这个问题,直到明天早上。
-
@nicola 这将给我一个列表,并进一步将其转换为循环或其他所需的向量
-
@user110244 请记住,
NROW(data$open_times[1])不能返回 2。NROW(data$open_times[[1]])可以,但前提是data$open_times是list(在我的评论中)。跨度> -
感谢您通知错字。我已经纠正了我的错误。
标签: r for-loop time data.table time-series