【问题标题】:Collapsing columns sharing unique value (s) in R在 R 中折叠共享唯一值的列
【发布时间】:2021-06-25 18:32:10
【问题描述】:

如何折叠行列,让它们共享唯一值?

我有一个这样的数据框:

Group   Status  Temperature     Ref
A       Moving                  1   
A               Cold            1   
B       Static                  1   
B               Warm            2   
C       Static  Temperate       3   
C               Temperate       3

而我想要的输出是

Group   Status  Temperature     Ref
A       Moving  Cold            1   
B       Static  Warm            1;2
C       Static  Temperate       3   

这应该很简单,但是当我这样做时

aggregate(df$Temperature, list(df$Group), paste, collapse=",")

df %>%
  group_by(Group) %>%
  summarise(Temperature=paste(Temperature, collapse=''))

我只选择部分列,具体取决于我选择的列。

【问题讨论】:

    标签: r dataframe duplicates unique collapse


    【解决方案1】:

    这个怎么样:

    library(tidyr)
    
    df %>% 
        mutate_at(vars(Status, Temperature), list(~ifelse(.=="", NA, .))) %>% 
        group_by(Group) %>% 
        fill(Status, Temperature, .direction = "downup") %>% 
        group_by(Group, Status, Temperature) %>%
        unique %>% 
        summarise(Ref = paste(Ref, collapse = ";"))
    
    

    警告:此代码首先将 StatusTemperature 中的空值转换为 NA,然后填充该值,假设每个 Group 只有一个 StatusTemperature 值。

    【讨论】:

    • 谢谢!确实非常接近,但是如果状态和温度有一些不同的值呢?我刚刚检查了我的数据,确实有不同的值..
    • 那你能澄清一下你想让代码做什么吗? (也许更新示例数据框和所需的输出)
    • 另外请以可重现的格式提供数据框! (即df <- data.frame(Group = ...)
    【解决方案2】:

    仅使用 summarise(across(... 连接所有非空白和 unique

    这样做

    df %>% group_by(Group) %>% summarise(across(everything(), ~ toString(unique(.[. != '']))))
    
    # A tibble: 3 x 4
      Group Status Temperature Ref  
    * <chr> <chr>  <chr>       <chr>
    1 A     Moving Cold        1    
    2 B     Static Warm        1, 2 
    3 C     Static Temperate   3
    
    

    dput(df) 使用的是

    df <- structure(list(Group = c("A", "A", "B", "B", "C", "C"), Status = c("Moving", 
    "", "Static", "", "Static", ""), Temperature = c("", "Cold", 
    "", "Warm", "Temperate", "Temperate"), Ref = c(1L, 1L, 1L, 2L, 
    3L, 3L)), class = "data.frame", row.names = c(NA, -6L))
    

    【讨论】:

      猜你喜欢
      • 2021-12-24
      • 1970-01-01
      • 1970-01-01
      • 2018-07-31
      • 2020-03-22
      • 2016-09-28
      • 2018-01-15
      • 2013-05-22
      • 1970-01-01
      相关资源
      最近更新 更多