【问题标题】:Grouping of rows having same elements in a column of a dataframe在数据框的列中对具有相同元素的行进行分组
【发布时间】:2021-12-24 15:08:18
【问题描述】:

df 是一个数据框,我需要在其中将Name 列中具有相同元素的行组合在一起。最后要删除Name 列中的重复元素。

df <- data.frame(Name = c("A","","","B","","","A","","","B","",""),
                 Test = c("test1","test2","test3","test1","test2","test3",
                       "test1.1","test2.1","test3.1","test1.1","test2.1","test3.1"))

期望的输出:

> df
   Name    Test
1     A   test1
2         test2
3         test3
4       test1.1
5       test2.1
6       test3.1
7     B   test1
8         test2
9         test3
10      test1.1
11      test2.1
12      test3.1

【问题讨论】:

  • 这是什么原因,比如某处发布的表格?如果是这样,kableExtra 具有用于格式化此类表格的功能,但它适用于 Latex 或 HTML 文档。否则,从数据管理的角度来看,这似乎是个坏主意

标签: r dataframe


【解决方案1】:

您可以使用tidyverse 尝试以下操作。将空字符值替换为NA,将fill 替换为Name 值。然后,按Name 排序。最后,只保留组中的第一个Name

library(tidyverse)

df %>%
  mutate(Name = na_if(Name, "")) %>%
  fill(Name, .direction = "down") %>%
  arrange(match(Name, unique(df$Name))) %>%
  group_by(Name) %>%
  mutate(Name = ifelse(row_number() == 1, Name, ""))

输出

   Name  Test   
   <chr> <chr>  
 1 "A"   test1  
 2 ""    test2  
 3 ""    test3  
 4 ""    test1.1
 5 ""    test2.1
 6 ""    test3.1
 7 "B"   test1  
 8 ""    test2  
 9 ""    test3  
10 ""    test1.1
11 ""    test2.1
12 ""    test3.1

【讨论】:

  • 谢谢。这工作正常。我想知道是否有办法保持“名称”列中元素的顺序不变。您的解决方案按字母顺序对“名称”列中的元素进行排序。如果用“Z”代替“A”,用“Y”代替“B”,我希望它的顺序相同,即 Z 在上,Y 在下。
  • @AbhishekChowdhury 查看编辑后的答案。您可以将arrange 更改为按Name 的原始顺序排序。看看这是否会给你想要的行为。
  • 完美!感谢您的帮助
【解决方案2】:

这是na.locfarrange 的一个选项

library(dplyr)
library(zoo)
df %>%
  arrange(na.locf(na_if(Name, ""))) %>%
  mutate(Name = replace(Name, duplicated(Name) & Name != "", ""))

-输出

  Name    Test
1     A   test1
2         test2
3         test3
4       test1.1
5       test2.1
6       test3.1
7     B   test1
8         test2
9         test3
10      test1.1
11      test2.1
12      test3.1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-02
    • 1970-01-01
    • 2020-11-05
    • 2021-12-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多