在R中的不同列中插入重复项和不重复项

时间:2019-01-25 20:50:01

标签: r dplyr

我有以下数据,希望您能帮我,因为我在堆栈溢出中找不到我的解决方案。

ID	Code
1	A
1	A12
2	M
3	A
2	M12
4	A12
5	M12
6	M
7	A
6	M12

如您所见,有些ID是重复的,有些不是。我想生成一些列以查看特定列中的每个代码。理想的结果是:

ID	Code	A1	A121	M1	M121
1	A	A	N/A	N/A	N/A
1	A12	N/A	A12	N/A	N/A
2	M	N/A	N/A	M	N/A
3	A	A	N/A	N/A	N/A
2	M12	N/A	N/A	N/A	M12
4	A12	N/A	A12	N/A	N/A
5	M12	N/A	N/A	N/A	M12
6	M	N/A	N/A	M	N/A
7	A	A	N/A	N/A	N/A
6	M12	N/A	N/A	N/A	M12

我了解您要我展示自己的尝试。不幸的是,我作为新手无法做到。非常感谢您的帮助。

2 个答案:

答案 0 :(得分:2)

应该是

library(tidyverse)

df <- tribble(~ID, ~Code,
              1, "A",
              1, "A12",
              2, "M",
              3, "A",
              2, "M12",
              4, "A12",
              5, "M12",
              6, "M",
              7, "A",
              6, "M12")

df %>%
  spread(key = Code, value = Code)

结果

# A tibble: 7 x 5
     ID A     A12   M     M12  
  <dbl> <chr> <chr> <chr> <chr>
1     1 A     A12   NA    NA   
2     2 NA    NA    M     M12  
3     3 A     NA    NA    NA   
4     4 NA    A12   NA    NA   
5     5 NA    NA    NA    M12  
6     6 NA    NA    M     M12  
7     7 A     NA    NA    NA   

许多人希望对列进行1/0编码,那么解决方案是

df %>%
 mutate(bin = 1) %>%
 spread(key = Code, value = bin, fill = 0)

# A tibble: 7 x 5
     ID     A   A12     M   M12
  <dbl> <dbl> <dbl> <dbl> <dbl>
1     1     1     1     0     0
2     2     0     0     1     1
3     3     1     0     0     0
4     4     0     1     0     0
5     5     0     0     0     1
6     6     0     0     1     1
7     7     1     0     0     0

答案 1 :(得分:1)

使用dplyrtidyr,您可以像这样分散Code列:

df %>% 
    mutate(id_temp = row_number(), code_temp = Code) %>%
    spread(code_temp, code_temp) %>%
    select(-id_temp)

#    ID Code    A  A12    M  M12
# 1   1    A    A <NA> <NA> <NA>
# 2   1  A12 <NA>  A12 <NA> <NA>
# 3   2    M <NA> <NA>    M <NA>
# 4   2  M12 <NA> <NA> <NA>  M12
# 5   3    A    A <NA> <NA> <NA>
# 6   4  A12 <NA>  A12 <NA> <NA>
# 7   5  M12 <NA> <NA> <NA>  M12
# 8   6    M <NA> <NA>    M <NA>
# 9   6  M12 <NA> <NA> <NA>  M12
# 10  7    A    A <NA> <NA> <NA>