【问题标题】:Merge partial rows while keeping the rest合并部分行,同时保留其余行
【发布时间】:2022-12-10 04:31:53
【问题描述】:

我想合并一些行,同时保留其余行和列的顺序。

df1 <- data.frame(by1=c(1,3,5,7,9),
                 by2=c(6:10),
                 x=c("a",NA_character_,NA_character_,NA_character_,"e"),
                 y=c("q","w","e","r","t"),stringsAsFactors = F)
df1
  by1 by2    x y
1   1   6    a q
2   3   7 <NA> w
3   5   8 <NA> e
4   7   9 <NA> r
5   9  10    e t


df2 <- data.frame(by1=c(3,5),x=c("b","c"),stringsAsFactors = F)
df2
  by1 x
1   3 b
2   5 c

预期输出:

expected <- data.frame(by1=c(1,3,5,7,9),
                       by2=c(6:10),
                       x=c("a","b","c",NA_character_,"e"),
                       y=c("q","w","e","r","t"),stringsAsFactors = F )
expected
  by1 by2    x y
1   1   6    a q
2   3   7    b w
3   5   8    c e
4   7   9 <NA> r
5   9  10    e t

我可以使用以下代码获得预期的输出。但是,它并不干净:

df1%>%
  merge(df2%>%rename(x2=x),by="by1",all.x=T)%>%
  mutate(x=coalesce(x,x2))%>%
  select(-x2)

【问题讨论】:

    标签: r dataframe


    【解决方案1】:

    使用rows_update

    library(dplyr)
    rows_update(df1, df2)
    

    -输出

      by1 by2    x y
    1   1   6    a q
    2   3   7    b w
    3   5   8    c e
    4   7   9 <NA> r
    5   9  10    e t
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-08-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-28
      • 1970-01-01
      相关资源
      最近更新 更多