简体   繁体   English

如何根据 ID 自加入/合并行? R Dplyr

[英]How to self-join/merge rows based on ID? R Dplyr

I have some ugly data that I'm working with that looks like this.我有一些丑陋的数据正在处理,看起来像这样。

在此处输入图像描述

My Goal is to get this我的目标是得到这个

在此处输入图像描述

Here is my code and I tried doing an inner_join and full_join but I couldn't get only 3 rows.这是我的代码,我尝试做一个 inner_join 和 full_join 但我不能只得到 3 行。


data <- data.frame("ID" = c(11,11,22,22,33,33),
           "Time 1" = c(131, NA, NA, NA, 177, 177),
           "Time 2" = c(NA, 145, 342, 342, NA, 187),
           "Time 3" = c(NA, 165,NA, 412, 212, 212))

data <- inner_join(data, data, by = "ID")

Perhaps this helps也许这有帮助

library(dplyr)
data %>% group_by(ID) %>% summarise(across(everything(), ~ if(all(is.na(.))) NA_real_ else .[complete.cases(.)][1]))
library(tidyverse)
data %>%
  pivot_longer(-ID) %>%
  group_by(ID) %>% fill(value, .direction = "up") %>% ungroup() %>%
  pivot_wider(names_from = "name", values_from = "value", values_fn = max)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM