【问题标题】:How to get the next elements of duplicated values in data frame in r?如何在r中获取数据框中重复值的下一个元素?
【发布时间】:2019-09-20 01:32:59
【问题描述】:

我想删除A列中的重复元素,我需要合并新列中重复值的相关元素 我有这个数据框:

A   B   Repeat
a   x1  5
a   x5  5
a   x4  5
a   x2  5
a   x3  5
b   x2  3
b   x4  3
b   x1  3
c   x5  3
c   x9  3
c   x3  3
d   x2  2
d   x8  2
e   x5  2
e   x1  2
f   x6  1
g   x2  1
h   x5  1
i   x4  1
j   x7  1

这是我预期的数据框:

A   Repeat  Merged values of B
a   5   x1,x5,x4,x2,x3
b   3   x2,x4,x1
c   3   x5,x9,x3
d   2   x2,x8
e   2   x5,x1
f   1   x6
g   1   x2
h   1   x5
i   1   x4
j   1   x7

【问题讨论】:

  • 不,我不需要 B 列

标签: r dataframe merge duplicates


【解决方案1】:

使用 dplyr ,我们可以 group_by A 并使用 toStringB 创建一个逗号分隔的值,并获得 first 的值 Repeat

library(dplyr)

df %>% 
  group_by(A) %>%
  summarise(new_B = toString(B),
            Repeat = first(Repeat))


# A tibble: 10 x 3
#    A     new_B              Repeat
#   <fct> <chr>               <int>
# 1 a     x1, x5, x4, x2, x3      5
# 2 b     x2, x4, x1              3
# 3 c     x5, x9, x3              3
# 4 d     x2, x8                  2
# 5 e     x5, x1                  2
# 6 f     x6                      1
# 7 g     x2                      1
# 8 h     x5                      1
# 9 i     x4                      1
#10 j     x7                      1

【讨论】:

    【解决方案2】:

    我们可以通过data.table 做到这一点

    library(data.table)
    setDT(df)[, .(new_B = toString(B), Repeat = first(Repeat)), A]
    #    A              new_B Repeat
    # 1: a x1, x5, x4, x2, x3      5
    # 2: b         x2, x4, x1      3
    # 3: c         x5, x9, x3      3
    # 4: d             x2, x8      2
    # 5: e             x5, x1      2
    # 6: f                 x6      1
    # 7: g                 x2      1
    # 8: h                 x5      1
    # 9: i                 x4      1
    #10: j                 x7      1
    

    数据

    df <- structure(list(A = c("a", "a", "a", "a", "a", "b", "b", "b", 
    "c", "c", "c", "d", "d", "e", "e", "f", "g", "h", "i", "j"), 
        B = c("x1", "x5", "x4", "x2", "x3", "x2", "x4", "x1", "x5", 
        "x9", "x3", "x2", "x8", "x5", "x1", "x6", "x2", "x5", "x4", 
        "x7"), Repeat = c(5L, 5L, 5L, 5L, 5L, 3L, 3L, 3L, 3L, 3L, 
        3L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L)),
        class = "data.frame", row.names = c(NA, 
    -20L))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-08-18
      • 2020-03-15
      • 1970-01-01
      • 1970-01-01
      • 2013-02-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多