【问题标题】:R - Display unique values in a column rather than count them, within summarize (dplyr pipe)R - 在汇总(dplyr 管道)中在一列中显示唯一值而不是计算它们
【发布时间】:2018-09-07 09:25:38
【问题描述】:

我想重塑我的数据,使与另一列相关的一列中的地区值显示在新创建的列中

df
     A    B  
1  <NA> <NA>
2    a    b
3    a    d
4    b    c

类似于:

> df %>% 
+   group_by(A) %>% 
+   summarise(n_distinct(B))
# A tibble: 3 x 2
     A     `n_distinct(B)`
   <chr>           <int>
  1 a                   2
  2 b                   1
  3 NA                  1

但不是计算出现次数,而是在新列中显示实际值?

类似于以下内容:

df
     A    B
1   <NA> <NA>
2    a    b  **d**
4    b    c

我尝试传播,但它不起作用,出现以下错误:

错误:行的标识符重复

我的两列都是因子,但如果需要可以重新分类。

谢谢!

【问题讨论】:

    标签: r dplyr reshape


    【解决方案1】:
    library(dplyr)
    library(tidyr)
    df %>% group_by(A) %>% summarise(B=paste0(unique(B), collapse = ',')) %>% 
           separate(B,into = paste0('B',1:2))
    
    # A tibble: 3 x 3
    A     B1    B2   
    <chr> <chr> <chr>
    1 a     b     d    
    2 b     c     NA   
    3 NA    NA    NA   
    Warning message:
    Expected 2 pieces. Missing pieces filled with `NA` in 2 rows [2, 3]. 
    

    【讨论】:

    • @SapirGreenberg,然后请用新数据和预期输出更新您的问题。
    【解决方案2】:

    这是在创建序列列后使用spread 的选项

    library(tidyverse)
    df %>%
       group_by(A)  %>% 
       mutate(n1 = paste0("B", row_number())) %>%
       ungroup %>% 
       spread(n1, B)
    # A tibble: 3 x 3
    #  A     B1    B2   
    #  <fct> <fct> <fct>
    #1 a     b     d    
    #2 b     c     <NA> 
    #3 <NA>  <NA>  <NA> 
    

    数据

    df <- data.frame(A = c(NA, 'a', 'a', 'b'), B = c(NA, 'b', 'd', 'c'))
    

    【讨论】:

    • 难以置信!!非常感谢!这正是我想要实现的。 @akrun
    猜你喜欢
    • 1970-01-01
    • 2018-12-08
    • 1970-01-01
    • 2023-01-16
    • 2014-11-19
    • 1970-01-01
    • 2021-09-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多