假设我有一个数据集,其中graph_id为0到800
x y index graph_id
1 3327 535 0_0 0
2 3316 529 0_1 0
3 3307 2359 0_2 0
4 3296 652 0_3 0
5 3283 2999 0_4 0
6 3281 73 0_5 0
,我想使用基于graph_id的每个子数据集作为管道中mutate的输入。 像这样:
test <- data %>%
group_by(graph_id) %>%
select(x, y) %>%
dist()
但是,当然,我遇到了一个错误(因为dist适用于所有数据集,而不是子集):
Adding missing grouping variables: `graph_id`
Error: cannot allocate vector of size 20.9 Gb
所以
是否可以仅使用dplyr而不执行lapply来执行此类操作?
更新
这个想法是基于子数据框创建新列而不创建其他变量。如果您在mutate(以我为例)中进行操作,则可以使用{.}
处理初始数据帧:
data <-
data %>%
mutate(id = {.} %>%
group_by(graph_id) %>%
select(x, y) %>%
do(a = dist(.) %>%
as.matrix() %>%
melt(varnames = c("row", "col")) %>%
mutate(weight = 1/value *100) %>%
filter(row < col) %>%
rename(from = row,
to = col) %>%
graph_from_data_frame(directed = F) %>%
fastgreedy.community() %>%
membership()) %>%
.['a'] %>%
unlist() %>%
unname())