合并具有所有变量组合的数据框列

时间:2019-02-23 19:49:04

标签: r dataframe

 "w" "n" 
    "1" 2 1 
    "2" 3 1 
    "3" 4 1 
    "4" 2 1 
    "5" 5 1 
    "6" 6 1 
    "7" 3 2 
    "8" 7 2 

我尝试了以下命令,但是没有显示任何更改。

w2 <- w1 %>%
expand(w,n)

我的输出应该像这样

w n 
2 1  
2 2  
3 1  
3 2  
4 1  
4 2  
5 1  
5 2  
6 1  
6 2  
7 1 
7 2 

数据

w1 <- structure(list(w = c(2L, 3L, 3L, 4L, 5L, 6L, 7L), n = c(1L, 1L, 
2L, 1L, 1L, 1L, 2L)), .Names = c("w", "n"), row.names = c(NA, 
-7L), class = c("grouped_df", "tbl_df", "tbl", "data.frame"), groups = structure(list(
    w = c(2L, 3L, 3L, 4L, 5L, 6L, 7L), n = c(1L, 1L, 2L, 1L, 
    1L, 1L, 2L), .rows = list(1L, 2L, 3L, 4L, 5L, 6L, 7L)), .Names = c("w", 
"n", ".rows"), row.names = c(NA, -7L), class = c("tbl_df", "tbl", 
"data.frame"), .drop = TRUE))

3 个答案:

答案 0 :(得分:2)

问题出在您对数据框进行分组时,请考虑:

w1 %>% 
  ungroup() %>%
  expand(w, n)

输出:

# A tibble: 12 x 2
       w     n
   <int> <int>
 1     2     1
 2     2     2
 3     3     1
 4     3     2
 5     4     1
 6     4     2
 7     5     1
 8     5     2
 9     6     1
10     6     2
11     7     1
12     7     2

答案 1 :(得分:0)

我们可以使用complete中的tidyr

library(dplyr)
library(tidyr)

dat2 <- dat %>%
  distinct(w, .keep_all = TRUE) %>%
  complete(w, n) 
dat2
# # A tibble: 12 x 2
#        w     n 
#    <int> <int>
#  1     2     1
#  2     2     2
#  3     3     1
#  4     3     2
#  5     4     1
#  6     4     2
#  7     5     1
#  8     5     2
#  9     6     1
# 10     6     2
# 11     7     1
# 12     7     2

数据

dat <- read.table(text = "w n 
                  2 1 
                  3 1 
                  4 1 
                  2 1 
                  5 1 
                  6 1 
                  3 2 
                  7 2",
                  header = TRUE)

答案 2 :(得分:0)

使用原始数据帧df,您可以创建一个新数据帧,为每个w的唯一值复制n

data.frame(w = rep(unique(df$w), 
                   each = uniqueN(df$n)),
           n = rep(unique(df$n),
                   times = uniqueN(df$w)))

输出:

   w n
1  2 1
2  2 2
3  3 1
4  3 2
5  4 1
6  4 2
7  5 1
8  5 2
9  6 1
10 6 2
11 7 1
12 7 2