dplyr函数可合并重复的数据,删除丢失的数据并维护冲突的数据 [英] dplyr function to combine repeated data, remove missing data, and maintain conflicting data
本文介绍了dplyr函数可合并重复的数据,删除丢失的数据并维护冲突的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个数据集,其中某些条目不止一次出现,有时其中一个条目中的数据丢失,而另一个条目中的数据丢失,有时完全丢失的数据,有时数据冲突.
I have a dataset where some entries appear more than once, sometimes with data in one entry that is missing in another, sometimes with completely missing data, and sometimes with conflicting data:
# A tibble: 9 x 4
ID name age fsm
<chr> <chr> <dbl> <dbl>
1 0001 Peter 13 NA
2 0001 NA 13 1
3 0001 Barry 13 1
4 0002 Jane 13 1
5 0002 Jane NA 1
6 0003 Billy 12 0
7 0003 Billy 12 1
8 0004 Sally 12 NA
9 0004 Sally 12 NA
我想将条目与丢失的数据(例如0001和0002)组合起来,维护有冲突的数据(0003),并维护将NA翻倍的数据(0004).要产生这个:
I would like to combine entries with missing data (e.g. 0001 and 0002), maintain conflicting data (0003) and maintain data that double NA (0004). To produce this:
# A tibble: 9 x 4
ID name age fsm
<chr> <chr> <dbl> <dbl>
1 0001 Peter 13 1
2 0001 Barry 13 1
3 0002 Jane 13 1
4 0003 Billy 12 0
5 0003 Billy 12 1
6 0004 Sally 12 NA
在此基础上:如何将重复的行与缺少的字段R合并
我写了以下内容:
tmp %>%
group_by(ID) %>%
summarise(across(everything(), ~ ifelse(length(na.omit(.x)) == 0, NA, na.omit(.x)))) %>%
distinct()
但它输掉了两次输入0003
But it loses the double entry, 0003
ID name age fsm
<chr> <chr> <dbl> <dbl>
1 0001 Peter 13 1
2 0002 Jane 13 1
3 0003 Billy 12 0
4 0004 Sally 12 NA
数据作为吞吐量:
structure(list(ID = c("0001", "0001", "0001", "0002", "0002",
"0003", "0003", "0004", "0004"), name = c("Peter", NA, "Barry",
"Jane", "Jane", "Billy", "Billy", "Sally", "Sally"), age = c(13,
13, 13, 13, NA, 12, 12, 12, 12), fsm = c(NA, 1, 1, 1, 1, 0, 1,
NA, NA)), class = c("spec_tbl_df", "tbl_df", "tbl", "data.frame"
), row.names = c(NA, -9L), spec = structure(list(cols = list(
ID = structure(list(), class = c("collector_character", "collector"
)), name = structure(list(), class = c("collector_character",
"collector")), age = structure(list(), class = c("collector_double",
"collector")), fsm = structure(list(), class = c("collector_double",
"collector"))), default = structure(list(), class = c("collector_guess",
"collector")), skip = 1L), class = "col_spec"))
推荐答案
您是否正在寻找这种解决方案?
Are you looking for this kind of solution?
library(tidyverse)
df %>%
group_by(ID, name, age, fsm) %>%
mutate(dupe = n()>1) %>%
group_by(ID) %>%
dplyr::summarise(across(everything(), ~ ifelse(length(na.omit(.x)) == 0 & dupe == TRUE, NA, na.omit(.x)))) %>%
distinct() %>%
select(-dupe)
输出:
ID name age fsm
<chr> <chr> <dbl> <dbl>
1 0001 Peter 13 1
2 0001 Barry 13 1
3 0002 Jane 13 1
4 0003 Billy 12 0
5 0003 Billy 12 1
6 0004 Sally 12 NA
这篇关于dplyr函数可合并重复的数据,删除丢失的数据并维护冲突的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文