聚合数据框每一列的所有唯一值
Aggregating all unique values of each column of data frame
我有一个大数据框(1616610 行,255 列),我需要根据键将每列的唯一值粘贴在一起。
例如:
> data = data.frame(a=c(1,1,1,2,2,3),
b=c("apples", "oranges", "apples", "apples", "apples", "grapefruit"),
c=c(12, 22, 22, 45, 67, 28),
d=c("Monday", "Monday", "Monday", "Tuesday", "Wednesday", "Tuesday"))
> data
a b c d
1 1 apples 12 Monday
2 1 oranges 22 Monday
3 1 apples 22 Monday
4 2 apples 45 Tuesday
5 2 apples 67 Wednesday
6 3 grapefruit 28 Tuesday
我需要聚合 255 列中每一列中的每个唯一值,并 return 一个新的数据框,每个唯一值都使用逗号分隔符。像这样:
a b c d
1 1 apples, oranges 12, 22 Monday
2 2 apples 45, 67 Tuesday, Wednesday
3 3 grapefruit 28 Thursday
我试过使用 aggregate
,像这样:
output <- aggregate(data, by=list(data$a), paste, collapse=", ")
但是对于这种大小的数据框来说,它太耗时了(几个小时),而且很多时候我不得不一起终止进程。最重要的是,这将聚合所有值,而不仅仅是唯一值。有没有人有任何提示:
1) 如何提高大数据集聚合的时间
2) 然后获取每个字段的唯一值
顺便说一句,这是我第一次 post 关于 SO,感谢您的耐心等待。
您可以使用 dplyr
执行以下操作
func_paste <- function(x) paste(unique(x), collapse = ', ')
data %>%
group_by(a) %>%
summarise_each(funs(func_paste))
## a b c d
## (dbl) (chr) (chr) (chr)
##1 1 apples, oranges 12, 22 Monday
##2 2 apples 45, 67 Tuesday, Wednesday
##3 3 grapefruit 28 Tuesday
从评论中移出:
library(data.table)
dt <- as.data.table(data)
dt[, lapply(.SD, function(x) toString(unique(x))), by = a]
给予:
a b c d
1: 1 apples, oranges 12, 22 Monday
2: 2 apples 45, 67 Tuesday, Wednesday
3: 3 grapefruit 28 Tuesday
我有一个大数据框(1616610 行,255 列),我需要根据键将每列的唯一值粘贴在一起。
例如:
> data = data.frame(a=c(1,1,1,2,2,3),
b=c("apples", "oranges", "apples", "apples", "apples", "grapefruit"),
c=c(12, 22, 22, 45, 67, 28),
d=c("Monday", "Monday", "Monday", "Tuesday", "Wednesday", "Tuesday"))
> data
a b c d
1 1 apples 12 Monday
2 1 oranges 22 Monday
3 1 apples 22 Monday
4 2 apples 45 Tuesday
5 2 apples 67 Wednesday
6 3 grapefruit 28 Tuesday
我需要聚合 255 列中每一列中的每个唯一值,并 return 一个新的数据框,每个唯一值都使用逗号分隔符。像这样:
a b c d
1 1 apples, oranges 12, 22 Monday
2 2 apples 45, 67 Tuesday, Wednesday
3 3 grapefruit 28 Thursday
我试过使用 aggregate
,像这样:
output <- aggregate(data, by=list(data$a), paste, collapse=", ")
但是对于这种大小的数据框来说,它太耗时了(几个小时),而且很多时候我不得不一起终止进程。最重要的是,这将聚合所有值,而不仅仅是唯一值。有没有人有任何提示:
1) 如何提高大数据集聚合的时间
2) 然后获取每个字段的唯一值
顺便说一句,这是我第一次 post 关于 SO,感谢您的耐心等待。
您可以使用 dplyr
func_paste <- function(x) paste(unique(x), collapse = ', ')
data %>%
group_by(a) %>%
summarise_each(funs(func_paste))
## a b c d
## (dbl) (chr) (chr) (chr)
##1 1 apples, oranges 12, 22 Monday
##2 2 apples 45, 67 Tuesday, Wednesday
##3 3 grapefruit 28 Tuesday
从评论中移出:
library(data.table)
dt <- as.data.table(data)
dt[, lapply(.SD, function(x) toString(unique(x))), by = a]
给予:
a b c d
1: 1 apples, oranges 12, 22 Monday
2: 2 apples 45, 67 Tuesday, Wednesday
3: 3 grapefruit 28 Tuesday