tidyr reshape tibble没有expand.grid

时间:2017-10-24 13:48:02

标签: r dplyr tidyr

我想在不使用expand.grid的情况下重塑一个tibble。虽然expand.grid +删除缺少的obs + delete“翻转重复”(即a,b与b相同,a)应该有效,但如果我有很多组合,计算速度会很慢。

这是我想要实现的虚拟版本:

library(dplyr)
library(tidyr)

initial_data <- tibble(x = c("east","east","east"), y = c("a","b","c"), z = c(0.1,0.2,0.3))

> initial_data
# A tibble: 3 x 3
      x     y     z
  <chr> <chr> <dbl>
1  east     a   0.1
2  east     b   0.2
3  east     c   0.3

final_data <- tibble(x = c("east","east","east"), y1 = c("a","a","b"), y2 = c("b","c","c"), z1 = c(0.1,0.1,0.2), z2 = c(0.2,0.3,0.3))

> final_data
# A tibble: 3 x 5
      x    y1    y2    z1    z2
  <chr> <chr> <chr> <dbl> <dbl>
1  east     a     b   0.1   0.2
2  east     a     c   0.1   0.3
3  east     b     c   0.2   0.3

这样可行,但效率极低:

expand_data <- as_tibble(expand.grid(initial_data$x, initial_data$y, initial_data$y)) %>% 
  filter(Var2 != Var3) %>% 
  distinct()

index <- !duplicated(t(apply(expand_data, 1, sort)))
expand_data <- expand_data[index, ] %>% 
  left_join(initial_data, by = c("Var1" = "x", "Var2" = "y")) %>% 
  left_join(initial_data, by = c("Var1" = "x", "Var3" = "y"))

> expand_data
# A tibble: 3 x 5
   Var1  Var2  Var3   z.x   z.y
  <chr> <chr> <chr> <dbl> <dbl>
1  east     b     a   0.2   0.1
2  east     c     a   0.3   0.1
3  east     c     b   0.3   0.2

非常感谢提前!!

3 个答案:

答案 0 :(得分:1)

如果要inner join然后过滤唯一组合呢?

library(dplyr)
inner_join(initial_data, initial_data,
           suffix = c('1', '2'), by = 'x') %>%
    filter(y1 < y2) %>%
    select(x, y1, y2, z1, z2)

#      x y1 y2  z1  z2
# 1 east  a  b 0.1 0.2
# 2 east  a  c 0.1 0.3
# 3 east  b  c 0.2 0.3

答案 1 :(得分:1)

此基础R解决方案是否适合您?:

data.frame(x = rep("east", 3),
           matrix(rep(initial_data$y, each = 2), 3), 
           matrix(rep(initial_data$z, each = 2), 3))

#      x X1 X2 X1.1 X2.1
# 1 east  a  b  0.1  0.2
# 2 east  a  c  0.1  0.3
# 3 east  b  c  0.2  0.3

答案 2 :(得分:1)

我会尝试combn,并结合purrr::map

您的数据

initial_data <- tibble(x = c("east","east","east"), y = c("a","b","c"), z = c(0.1,0.2,0.3))

解决方案

initial_data %>%
  nest(-x) %>%
  mutate(data = map(data, ~cbind(as_tibble(t(combn(.x$y, 2))) %>% setNames(paste0("y", 1:2)), 
                        as_tibble(t(combn(initial_data$z, 2))) %>% setNames(paste0("z", 1:2))) )) %>%
  unnest(data)

输出

# A tibble: 3 x 5
      # x    y1    y2    z1    z2
  # <chr> <chr> <chr> <dbl> <dbl>
# 1  east     a     b   0.1   0.2
# 2  east     a     c   0.1   0.3
# 3  east     b     c   0.2   0.3